美文网首页
leetcode 剑指 Offer 36. 二叉搜索树与双向链表

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

作者: flood_d | 来源:发表于2021-02-06 11:16 被阅读0次

0.code

/*
// 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;
        }
        head = root;
        dfs(root);
        head.left = pre;
        pre.right = head;
        return head;
    }
    public void dfs(Node root){
        if(root==null){
            return;
        }
        dfs(root.left);
        if(pre==null){
            head = root;
            pre = head;
        }else{
            pre.right = root;
            root.left = pre;
        }
        pre = root;
        dfs(root.right);
    }
}

相关文章

网友评论

      本文标题:leetcode 剑指 Offer 36. 二叉搜索树与双向链表

      本文链接:https://www.haomeiwen.com/subject/prantltx.html