1. 程式人生 > >LF.43.In-order Traversal Of Binary Tree

LF.43.In-order Traversal Of Binary Tree

ive inter () turn 空間復雜度 ack emp 復雜度 blog

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