Leetcode 426 Convert Binary Search Tree to Sorted Doubly Linked List

Leetcode 426 Convert Binary Search Tree to Sorted Doubly Linked List

The left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list.

Approach 1: DFS InOrder + Recursion
Standard inorder recursion follows left -> node -> right order.
Processing here is basically to link the previous node with the current one, and because of that one has to track the last node which is the largest node in a new doubly linked list so far.

class Solution {
    
    Node first = null;
    Node last = null;
    
    public Node treeToDoublyList(Node root) {
        if (root == null) return null;
        helper(root);
        // the successor node of last node is first node.
        last.right = first;
        // the predecessor of first node is last node.
        first.left = last;
        
        return first;
        
    }
    
    public void helper(Node node){ // using InOrder DFS
        
        if(node == null)
            return;
        
        helper(node.left);
        
        if(first == null){
            first = node;
        }else{
            // the successor of last node is current node
            last.right = node;
            // the predecessor of current node is last node;
            node.left = last;
        }
        
        //current node becomes the last node
        last = node;
        
        helper(node.right);
        
    }
}

Time complexity : O(N) since each node is processed exactly once.
Space complexity : O(N), We have to keep a recursion stack of the size of the tree height, which is O(logN) for the best case of completely balanced tree and O(N) for the worst case of completely unbalanced tree.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值