LF.43.In-order Traversal Of Binary Tree

Posted davidnyc

tags:

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

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的主要内容,如果未能解决你的问题,请参考以下文章

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