美文网首页
二叉搜索树与双向链表

二叉搜索树与双向链表

作者: shuixingge | 来源:发表于2016-04-28 19:27 被阅读433次

思路:
中序遍历:把一棵二叉排序树看成三个部分,根节点,右子树,左子树,根节点的左指针指向左子树的形成链表的最后一个节点,根节点的右孩子指向右子树形成链表的第一个节点,再对左右递归进行上述操作。

Paste_Image.png
public class Solution {
     

    public TreeNode Convert(TreeNode root) {
      if(root==null)
            return null;
        if(root.left==null&&root.right==null)
            return root;
        // 1.将左子树构造成双链表,并返回链表头节点
        TreeNode left = Convert(root.left);
        TreeNode p = left;
        // 2.定位至左子树双链表最后一个节点
        while(p!=null&&p.right!=null){
            p = p.right;
        }
        // 3.如果左子树链表不为空的话,将当前root追加到左子树链表
        if(left!=null){
            p.right = root;
            root.left = p;
        }
        // 4.将右子树构造成双链表,并返回链表头节点
        TreeNode right = Convert(root.right);
        // 5.如果右子树链表不为空的话,将该链表追加到root节点之后
        if(right!=null){
            right.left = root;
            root.right = right;
        }
        return left!=null?left:root;  
    }
    
      
}

相关文章

网友评论

      本文标题:二叉搜索树与双向链表

      本文链接:https://www.haomeiwen.com/subject/uigcrttx.html