426. 将二叉搜索树转化为排序的双向链表_面试题36. 二叉搜索树与双向链表

问题

在这里插入图片描述

例子

在这里插入图片描述
在这里插入图片描述
思路
first为第一个结点,即最小值的结点
pre为每次操作结点时的前一个结点,最终变成最后一个结点,即最大值的结点

first可看作head,pre可看作cur,采用尾插法进行构造双向链表

  • 方法1
    $$

    $$

  • 方法2
    $$

    $$

代码

//方法1 递归
class Solution {
    private Node first;
    private Node pre;
    public Node treeToDoublyList(Node root) {
        if(root==null) return root;
        midOrder(root);
        //把第一个结点和最后一个结点连起来
        first.left = pre;
        pre.right = first;
        return first;
        
    }
    public void midOrder(Node root) {
        if(root==null) return;
        if(root.left!=null) midOrder(root.left);
        //对结点操作
        //第一个结点
        if(first==null) first=root;
        if(pre==null) pre = root;
        else{//不是第一个结点
           pre.right = root;
            root.left = pre;

            pre=root; 
        }
 
        if(root.right!=null) midOrder(root.right);
        
    }
}
//方法2 迭代
class Solution {
    public Node treeToDoublyList(Node root) {
        if(root==null) return null;
        Stack<Node> s = new Stack<>();
        Node node = root;
        Node first=null, pre=null;
        while(s.size()>0 || node!=null) {
            //如果结点不为空,把结点及其左结点都放入栈
            if(node!=null) {
                s.push(node);
                node = node.left;
            }else{//如果结点为空,弹出一个结点,将其值添加进list,此时以该结点为根的树只剩下右子树没有处理了
                node = s.pop();
                //对结点的操作
                if(first==null) first=node;
                if(pre==null) pre =node;
                else{
                    pre.right = node;
                    node.left = pre;
                    pre = node;
                }
                //按照处理树的方式,处理剩下的右子树
                node = node.right;
            }
        }
        
        pre.right = first;
        first.left = pre;
        return first;
        
    }
}
发布了234 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/puspos/article/details/105203332