【LeetCode】【HOT】94. 二叉树的中序遍历(Morris 遍历)

【LeetCode】【HOT】94. 二叉树的中序遍历(Morris 遍历),第1张

【LeetCode】【HOT】94. 二叉树的中序遍历(Morris 遍历) 【LeetCode】【HOT】94. 二叉树的中序遍历

文章目录

【LeetCode】【HOT】94. 二叉树的中序遍历


package hot;

import java.util.ArrayList;
import java.util.List;

class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int val){
        this.val = val;
    }
}

public class Solution94 {
    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        node1.right = node2;
        node2.left = node3;
        Solution94 solution = new Solution94();
        System.out.println(solution.method(node1));
    }

    private List method(TreeNode root){
        List res = new ArrayList<>();
        TreeNode predecessor = null;

        while(root != null){
            if(root.left != null){
                predecessor = root.left;
                while(predecessor.right != null && predecessor.right != root){
                    predecessor = predecessor.right;
                }

                if(predecessor.right == null){
                    predecessor.right = root;
                    root = root.left;
                }else{
                    res.add(root.val);
                    predecessor.right = null;
                    root = root.right;
                }
            }else{
                res.add(root.val);
                root = root.right;
            }
        }
        return res;
    }
}

//时间复杂度为 O(n)
//空间复杂度为 O(1)

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5709787.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存