面试题:二叉树与双向搜索树

题目描述:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

思路1:递归

public class Solution{
    public TreeNode Convert(TreeNode root){
        if(root==null)return null;
        if(root.left==null&&root.right==null)return root;
        TreeNode left=Convert(root.left);//
        TreeNode p=left;
        while(p!=null&&p.right!=null){//左节点最右侧的值
            p=p.right;
        }
        if(left!=null){
         p.right=root;
          root.left=p;
        }
       TreeNode right=Convert(root.right);
       if(right!=null){
            root.right=right;
            right.left=root;
       }
      return left!=null?left:root; 
    }
}

思路2:中序遍历

public class Solution {
    TreeNode head = null;
    TreeNode realHead = null;
    public TreeNode Convert(TreeNode pRootOfTree) {
        ConvertSub(pRootOfTree);
        return realHead;
    }
     
    private void ConvertSub(TreeNode pRootOfTree) {
        if(pRootOfTree==null) return;
        ConvertSub(pRootOfTree.left);
        if (head == null) {
            head = pRootOfTree;
            realHead = pRootOfTree;
        } else {
            head.right = pRootOfTree;
            pRootOfTree.left = head;
            head = pRootOfTree;
        }
        ConvertSub(pRootOfTree.right);
    }
}

 

posted on 2018-08-25 21:09  Aaron12  阅读(196)  评论(0编辑  收藏  举报

导航