二叉搜索树和双向链表

参考https://www.nowcoder.com/questionTerminal/947f6eb80d944a84850b0538bf0ec3a5

题目描述

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

分析:题中要求输出排序的双向链表,因为在二叉搜索树的中序遍历是递增的,所以想到使用中序遍历,从小到大逐个找个节点,然后创建双向链表。过程中有一个小细节,就是创建双向链表完要返回双向链表的头节点,所以创建过程中要保存头节点。

代码实现:

public class Solution {
    public TreeNode Convert(TreeNode root) {
        if(root==null)
            return null;
        Stack<TreeNode> stack = new Stack<>();
        Boolean isFirst = true;
        TreeNode p = root;
        TreeNode pre = null;;
        while(p!=null||!stack.isEmpty()){
            while(p!=null){
                stack.push(p);
                p = p.left;
            }
            if(!stack.isEmpty()){
                p = stack.pop();
                //相对与非递归的中序遍历增加的代码
                if(isFirst==true){    //目的,记住头指针
                    root = p;
                    pre = p;
                    isFirst = false;
                }
                else{
                    pre.right = p;
                    p.left = pre;
                    pre = p;
                }
                ////////////
                p = p.right;
            }
        }
        return root;
    }
}

猜你喜欢

转载自blog.csdn.net/chenkaibsw/article/details/80721248