码迷,mamicode.com
首页 > 编程语言 > 详细

讲二次搜索树转化为排序的双向链表

时间:2019-01-15 14:09:37      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:搜索   节点   bin   class   turn   util   bean   算法   link   

package com.gylhaut.bean;

public class TreeNode<T> {
    public T data;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(T data) {
        this.left = null;
        this.right = null;
        this.data = data;
    }
}

 算法实现:

package com.gylhaut.util;

import com.gylhaut.bean.TreeNode;

public class BinaryTreeHelper {

    /**
     * 指向头节点
     * @param root
     * @return
     */
    public static TreeNode convert(TreeNode root){
        root=convert2Link(root);
        while (root.left != null){
            root = root.left;
        }
        return root;
    }

    /**
     * 搜索二叉树转成双向链表
     * @param root
     * @return
     */
    public static TreeNode convert2Link(TreeNode root){
        if(root == null|| (root.left == null && root.right == null)){
            return root;
        }
        TreeNode tmp = null;
        if(root.left != null){
           tmp= convert2Link(root.left);
           while (tmp.right != null){
               tmp = tmp.right;
           }
           tmp.right = root;
           root.left = tmp;
        }
        if (root.right !=null){
            tmp = convert2Link(root.right);
            while (tmp.left != null){
                tmp = tmp.left;
            }
            tmp.left = root;
            root.right = tmp;
        }

        return root;
    }

}

  

讲二次搜索树转化为排序的双向链表

标签:搜索   节点   bin   class   turn   util   bean   算法   link   

原文地址:https://www.cnblogs.com/gylhaut/p/10270880.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!