码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-03-31 00:40:42      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:XA   list   off   sem   log   one   style   pre   head   

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)

标签:XA   list   off   sem   log   one   style   pre   head   

原文地址:https://www.cnblogs.com/davidnyc/p/8679218.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!