zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    python -django 之第三方支付
    python 的排名,已经python的简单介绍
    第三方登录
    linux 基础命令
    JWT 加密
    Docker 简介
    中文分词库:结巴分词
    Django websocket 长连接使用
    jQuery截取字符串的几种方式
    Python 操作redis
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8679218.html
Copyright © 2011-2022 走看看