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

LF.43.In-order Traversal Of Binary Tree

时间:2018-03-30 23:04:26      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:public   时间   lis   sem   add   span   binary   sed   example   

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

Examples

5

/ \

3 8

/ \ \

1 4 11

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

Corner Cases

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

 

interative: 时间复杂度: o(n) 每个点都走, 空间复杂度 o(n) 但是是在 heap 上

 1 public class Solution {
 2   public List<Integer> preOrder(TreeNode root) {
 3     // Write your solution here
 4     List<Integer> res = new ArrayList<>();
 5     if (root == null) {
 6         return res ;
 7     }
 8     Deque<TreeNode> stack = new LinkedList<>() ;
 9     stack.offerFirst(root) ;
10     while(!stack.isEmpty()){
11         TreeNode curr = stack.pollFirst() ;
12         res.add(curr.key);
13         if (curr.right != null) {
14             stack.offerFirst(curr.right);
15         }
16         if (curr.left != null) {
17             stack.offerFirst(curr.left);
18         }
19     }
20     return res ;
21   }
22 }

 recursive : time: o(n) for every node, space: o(h) on the stack:

 1 private List<Integer> preOrder_recur(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         res.add(root.key) ;
15         helper(root.left, res) ;
16         helper(root.right, res);
17     }

 

LF.43.In-order Traversal Of Binary Tree

标签:public   时间   lis   sem   add   span   binary   sed   example   

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

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