莫里斯·遍历是否多次访问一些节点?

发布于 2025-01-23 16:02:48 字数 1303 浏览 2 评论 0原文

我正在求解 leetcode inorder tree traversal in ordor tree traversal 并实现了Morris traversal 在解决方案页面上建议。这是:

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode() {}
    public TreeNode(int val) { this.val = val; }
    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public static List<Integer> inorderTraversalMorris(TreeNode root){
    if(root == null){
        return Collections.emptyList();
    }
    List<Integer> result = new ArrayList<>();
    TreeNode current = root;
    while(current != null){
        if(current.left != null){
            TreeNode next = current.left;
            TreeNode appendTo = next;
            while(appendTo.right != null){
                appendTo = appendTo.right;
            }
            current.left = null;
            appendTo.right = current;
            current = next;
        } else {
            result.add(current.val);
            current = current.right;
        }
    }

    return result;
}

我看到的问题是,在将树重新平衡为螺纹二进制树时,算法访问了两次节点。有可能避免它吗?

I'm solving LeetCode problem of inorder tree traversal and implemented Morris traversal as suggested on the solutions page. Here it is:

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode() {}
    public TreeNode(int val) { this.val = val; }
    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public static List<Integer> inorderTraversalMorris(TreeNode root){
    if(root == null){
        return Collections.emptyList();
    }
    List<Integer> result = new ArrayList<>();
    TreeNode current = root;
    while(current != null){
        if(current.left != null){
            TreeNode next = current.left;
            TreeNode appendTo = next;
            while(appendTo.right != null){
                appendTo = appendTo.right;
            }
            current.left = null;
            appendTo.right = current;
            current = next;
        } else {
            result.add(current.val);
            current = current.right;
        }
    }

    return result;
}

The problem I see is that while re-balancing the tree to be a Threaded binary tree the algorithm visits some nodes twice. Is it possible to avoid it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文