Convert Binary Search Tree to Sorted Doubly Linked List

Example 1:

Input: root = [4,2,5,1,3]

Output: [1,2,3,4,5]

思路:Inorder traverse,用stack做;记录一下first 和last node就可以了;最后返回dummpy.right;

/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val,Node _left,Node _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};
*/
class Solution {
    public Node treeToDoublyList(Node root) {
        if(root == null) {
            return null;
        }
        Stack<Node> stack = new Stack<Node>();
        Node node = root;
        while(node != null) {
            stack.push(node);
            node = node.left;
        }
        
        Node first = null;
        Node last = null;
        Node dummpy = new Node(0);
        Node cur = dummpy;
        while(!stack.isEmpty()) {
            node = stack.pop();
            
            if(first == null) {
                first = node;
            }
            if(stack.isEmpty()) {
                last = node;
            }
            cur.right = node;
            node.left = cur;
            cur = node;
            
            if(node.right != null) {
                node = node.right;
                while(node != null) {
                    stack.push(node);
                    node = node.left;
                }
            }
            
        }
        first.left = last;
        last.right = first;
        return dummpy.right;
    }
}
发布了663 篇原创文章 · 获赞 13 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/104604731