[LC] 426. Convert Binary Search Tree to Sorted Doubly Linked List

BST换排好序的任何数据结构用脚趾头想都应该是inorder的dfs。这里也就是dfs中间穿插一些前后连接的操作就行了。
给出两种解法,一个是递归做的,一个是用Stack做的。(意想不到的是递归的比Stack的要快)

    public Node treeToDoublyList(Node root) {
        if (root == null) return null;

        Node[] prev = new Node[1];
        Node[] newRoot = new Node[1];
        dfs(root, prev, newRoot);
        newRoot[0].left = prev[0];
        prev[0].right = newRoot[0];
        return newRoot[0];
    }
    
    public void dfs(Node current, Node[] prev, Node[] newRoot) {
        if (current != null) {
            dfs(current.left, prev, newRoot);
            if (newRoot[0] == null) {
                newRoot[0] = current;
            }
            
            if (prev[0] != null) {
                prev[0].right = current;
                current.left = prev[0];
            }
            
            prev[0] = current;
            dfs(current.right, prev, newRoot);
        }
    }
    public Node treeToDoublyList(Node root) {
        if (root == null) return null;

        Node current = root;
        Node prev = null, firstNode = null;
        Stack<Node> nodeStk = new Stack<>();
        while(current != null || !nodeStk.isEmpty()) {
            if (current != null) {
                nodeStk.push(current);
                current = current.left;
            } else {
                current = nodeStk.pop();
                if (firstNode == null) {
                    firstNode = current;
                }

                if (prev != null) {
                    prev.right = current;
                    current.left = prev;
                }
                prev = current;
                current = current.right;
            }
        }
        prev.right = firstNode;
        firstNode.left = prev;
        return firstNode;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值