剑指 Offer 36. 二叉搜索树与双向链表

思路:中序遍历依次修改左右连接。

剑指 Offer 36. 二叉搜索树与双向链表

/*
// 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 pre, head;
    public Node treeToDoublyList(Node root) {
        if(root == null)    return null;
        dfs(root);
        //首尾节点相连
        head.left = pre;
        pre.right = head;
        return head;
    }
    //类型为void
    void dfs(Node cur){
        if(cur == null) return;
        //中序遍历,此处会先访问到最左边的结点
        dfs(cur.left);
        //当pre为空时,cur访问到了循环链表第一个节点,此时保存为head
        if(pre == null) head = cur;
        //pre不为空,将pre.right连到cur上
        else pre.right = cur;
        //将cur.left连到pre上
        cur.left = pre;
        //pre移到下一个
        pre = cur;
        dfs(cur.right);
    }
}

 

posted @ 2021-04-02 14:02  星予  阅读(34)  评论(0编辑  收藏  举报