首页 > 编程语言 > 详细

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

时间:2019-01-15 12:50:05      阅读:176      评论:0      收藏:0      [点我收藏+]
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;
    }

}

  

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!