• LF.44.Pre-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.

    tree 结构的 空间复杂度,都需要考虑树的结构,o(h)是正确答案。

    interative: 时间复杂度: o(n) 每个点都走, 空间复杂度 o(h) 但是是在 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     }
  • 相关阅读:
    复杂json格式转化为javabean
    lambda常用方法
    solr设置分片和副本
    Python之Scrapy爬虫框架安装及简单使用
    40多个纯CSS绘制的图形
    windows下自动启动Redis隐藏命令行窗口
    用Webpack构建Vue项目
    上传本地代码到gitHub过程详解
    html/css常用合集
    数据库索引与b+树
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8678911.html
Copyright © 2020-2023  润新知