zoukankan      html  css  js  c++  java
  • Binary Tree Preorder Traversal

    Preorder: first, visit parent node, then, left child, last is to visit right child.

    Algorithm 1 -- DFS & Stack

    We can use stack to store left child and right child.

     1 public class Solution {
     2     public ArrayList<Integer> inorderTraversal(TreeNode root) {
     3         // IMPORTANT: Please reset any member data you declared, as
     4         // the same Solution instance will be reused for each test case.
     5          ArrayList<Integer> lst = new ArrayList<Integer>();
     6  
     7         if(root == null)
     8             return lst; 
     9  
    10         Stack<TreeNode> stack = new Stack<TreeNode>();
    11         //define a pointer to track nodes
    12         TreeNode p = root;
    13  
    14         while(!stack.empty() || p != null){
    15  
    16             // if it is not null, push to stack
    17             //and go down the tree to left
    18             if(p != null){
    19                 lst.add(p.val);
    20                 stack.push(p);
    21                 p = p.left;
    22             }else{
    23                 TreeNode t = stack.pop();
    24                 p = t.right;
    25             }
    26         }
    27  
    28         return lst;
    29     }
    30 }

    Algorithm 2 -- Recursive

     1 public class Solution {
     2     List<Integer> result = new ArrayList<Integer>();
     3  
     4     public List<Integer> preorderTraversal(TreeNode root) {
     5         if(root != null){
     6             helper(root);
     7         }
     8         return result;
     9     }
    10  
    11     public void helper(TreeNode p){
    12         result.add(p.val);
    13         if(p.left!=null)
    14             helper(p.left);
    15         if(p.right!=null)
    16             helper(p.right);
    17     }
    18 }    
    
    
  • 相关阅读:
    HiveServer2的配置使用
    hBase-thrift 实践(java)
    Building Apache Thrift on CentOS 6.5
    linux安装thrift
    Apache Thrift with Java Quickstart(thrift入门及Java实例)
    [转载]/etc/security/limits.conf解释及应用
    storm 入门原理介绍
    Storm的wordCounter计数器详解
    CentOS6.5 安装python
    HBase 协处理器统计行数
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4850600.html
Copyright © 2011-2022 走看看