LF.43.In-order Traversal Of Binary Tree(recur+iter)

Posted davidnyc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LF.43.In-order Traversal Of Binary Tree(recur+iter)相关的知识,希望对你有一定的参考价值。

Implement an iterative, in-order traversal of a given binary tree, return the list of keys of each node in the tree as it is in-order traversed.

Examples

5

/ \

3 8

/ \ \

1 4 11

In-order traversal is [1, 3, 4, 5, 8, 11]

Corner Cases

What if the given binary tree is null? Return an empty list in this case.

 

iterative:

 1 public List<Integer> inOrder(TreeNode root) {
 2     // Write your solution here
 3     List<Integer> res = new ArrayList<>() ;
 4     Deque<TreeNode> stack = new LinkedList<>() ;
 5     //helper is the one-step ahead for the root
 6     TreeNode helper = root ;
 7     while(helper != null || !stack.isEmpty()){
 8         if (helper != null) {
 9             stack.offerFirst(helper);
10             helper = helper.left ;
11         } else{
12             TreeNode curr = stack.pollFirst();
13             res.add(curr.key) ;
14             helper = curr.right ;
15         }
16     }
17     return res ;
18   }

 

recursive:

 1 private List<Integer> preOrder_iter(TreeNode root){
 2         List<Integer> res = new ArrayList<>() ;
 3         if (root == null) {
 4             return res ;
 5         }
 6         helper(root, res);
 7         return res ;
 8     }
 9     private void helper(TreeNode root , List<Integer> res ){
10             //base case
11         if (root == null) {
12             return ;
13         }
14         helper(root.left, res) ;
15         res.add(root.key) ;
16         helper(root.right, res);
17     }

 

以上是关于LF.43.In-order Traversal Of Binary Tree(recur+iter)的主要内容,如果未能解决你的问题,请参考以下文章

STUN(Session Traversal Utilities for NAT) 与 TURN(Traversal Using Relays around NAT)

将Level Order Traversal转换为完整二叉树的Inorder Traversal

Morris Traversal方法遍历

Lintcode: Matrix Zigzag Traversal

94. Binary Tree Inorder Traversal

[LeetCode]题解(python):107 Binary Tree Level Order Traversal II