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

94. 二叉树的中序遍历

作者: Andysys | 来源:发表于2019-12-29 00:22 被阅读0次
    image.png

    tag: 栈, 树, 哈希表

        // 递归
        public List<Integer> inorderTraversal1(TreeNode root) {
            List<Integer> list = new LinkedList<>();
            helper(root, list);
            return list;
        }
    
        private void helper(TreeNode node, List<Integer> list) {
            if (node == null) {
                return;
            }
            if (node.left != null) {
                helper(node.left, list);
            }
            list.add(node.val);
            if (node.right != null) {
                helper(node.right, list);
            }
        }
    
        // 迭代
        public List<Integer> inorderTraversal2(TreeNode root) {
            List<Integer> list = new LinkedList<>();
            Stack<TreeNode> stack = new Stack<>();
            TreeNode curr = root;
            while (curr != null || !stack.isEmpty()) {
                while (curr != null) {
                    stack.push(curr);
                    curr = curr.left;
                }
                curr = stack.pop();
                list.add(curr.val);
                curr = curr.right;
            }
            return list;
        }
    

    相关文章

      网友评论

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

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