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;
        return res;
    private void recur(Node root){
        if(root==null) return;
        Node tmp_root=new Node(root.val);

Insert picture description here

Guess you like

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