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

    (referrence: ProgramCreek)

    The key to solve inorder traversal of binary tree includes the following:

    1. The order of "inorder" is: left child -> parent -> right child
    2. Use a stack to track nodes
    3. Understand when to push node into the stack and when to pop node out of the stack

    Note that inorder traversal of BST is an ascending array.

    Algorithm 1 -- Recursive

     1 public class Solution {
     2     List<Integer> result = new ArrayList<Integer>();
     3  
     4     public List<Integer> inorderTraversal(TreeNode root) {
     5         if(root !=null){
     6             helper(root);
     7         }
     8  
     9         return result;
    10     }
    11  
    12     public void helper(TreeNode p){
    13         if(p.left!=null)
    14             helper(p.left);
    15  
    16         result.add(p.val);
    17  
    18         if(p.right!=null)
    19             helper(p.right);
    20     }
    21 }

    Algorithm 2 -- Iterative

     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                 stack.push(p);
    20                 p = p.left;
    21  
    22             // if no left child
    23             // pop stack, process the node
    24             // then let p point to the right
    25             }else{
    26                 TreeNode t = stack.pop();
    27                 lst.add(t.val);
    28                 p = t.right;
    29             }
    30         }
    31  
    32         return lst;
    33     }
    34 }
  • 相关阅读:
    如何重新加载 Spring Boot 上的更改,而无需重新启动服务器?
    FileUpload拦截器
    aspnet网页刷新
    查看SQL表的详细信息
    学习GDI+ (1)
    设计模式简单工厂模式
    对数据库表操作,统一的方法。
    随机产生300道四则运算
    略谈从计算机专业,再到软件构建的初识
    #在android studio中维护日程管理系统
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4845443.html
Copyright © 2011-2022 走看看