Convert Binary Search Tree to Sorted Doubly Linked List

本文介绍了一种将二叉搜索树转换为双向链表的方法,通过中序遍历并利用栈来实现节点之间的连接,最终形成一个循环的双向链表。此方法巧妙地使用了哑节点简化了代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Example 1:

Input: root = [4,2,5,1,3]

Output: [1,2,3,4,5]

思路:Inorder traverse,用stack做;记录一下first 和last node就可以了;最后返回dummpy.right;

错误点:没有想到用dummpy,作为cur 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 {
    public Node treeToDoublyList(Node root) {
        if(root == null) {
            return null;
        }
        Stack<Node> stack = new Stack<>();
        pushLeft(root, stack);
        
        Node first = null;
        Node last = null;
        Node pre = null;
        while(!stack.isEmpty()) {
            Node node = stack.pop();
            // get first;
            if(first == null) {
                first = node;
            }
            // get last;
            if(stack.isEmpty()) {
                last = node;
            }
            // connect middle node;
            if(pre != null) {
                pre.right = node;
                node.left = pre;
            }
            pre = node;
            if(node.right != null) {
                pushLeft(node.right, stack);
            }
        }
        
        first.left = last;
        last.right = first;
        return first;
    }
    
    private void pushLeft(Node node, Stack<Node> stack) {
        while(node != null) {
            stack.push(node);
            node = node.left;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值