LeetCode—Sword refers to Offer: Binary search tree and doubly linked list (in-order traversal)

Binary search tree and doubly linked list (medium)

September 2, 2020

Question source: Likou

Insert picture description here
Insert picture description here

Problem solving

Looking at the case, we want to find the node linked list of the binary search tree from small to large. At this time, we can think of the nodes extracted by the middle-order traversal (LDR) in the order of small to large.
Then naturally we can construct a linked list, but we also need to consider that the linked list is bidirectional, so we need to copy the current node every time in the recursion to create a relationship with the global node.
Finally, don't forget to establish a two-way relationship between the first node and the last node.

/*
// 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 {
    
    
    Node tmp_res=new Node();
    Node res=tmp_res;
    public Node treeToDoublyList(Node root) {
    
    
        if(root==null) return null;
        //中序遍历拿到节点
        recur(root);
        //初始化结果res
        res=res.right;
        //第一个节点和最后一个节点建立关系
        res.left=tmp_res;
        tmp_res.right=res;
        return res;
    }
    private void recur(Node root){
    
    
        if(root==null) return;
        recur(root.left);
        //复制当前节点
        Node tmp_root=new Node(root.val);
        //与结果节点建立联系
        tmp_res.right=tmp_root;
        tmp_root.left=tmp_res;
        //结果节点往右移动一步
        tmp_res=tmp_res.right;
        recur(root.right);
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_41541562/article/details/108369150