美文网首页
力扣 94 二叉树的中序遍历

力扣 94 二叉树的中序遍历

作者: zhaojinhui | 来源:发表于2020-11-13 03:19 被阅读0次

题意:中序遍历树

思路:用stack实现树的中序遍历非递归,具体见代码

思想:树的中序遍历

复杂度:时间O(n),空间O(n)

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        HashSet<TreeNode> set = new HashSet();
        List<Integer> res = new ArrayList();
        if(root == null)
            return res;
        
        stack.push(root);
        while(!stack.isEmpty()) {
            TreeNode cur = stack.peek();
            while(cur.left != null && !set.contains(cur.left)) {
                stack.push(cur.left);
                cur = cur.left;
            }
            cur = stack.pop();
            res.add(cur.val);
            set.add(cur);
            if(cur.right != null)
                stack.push(cur.right);
        }
        
        return res;
    }
}

相关文章

网友评论

      本文标题:力扣 94 二叉树的中序遍历

      本文链接:https://www.haomeiwen.com/subject/tkgsbktx.html