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 }
  • 相关阅读:
    由 基本数据型态转换成 String/ 由 String 转换成 数字的基本数据型态
    屏幕适配(UGUI)非UI
    转载 Unity Text 插入超链接
    File类的使用
    抽奖
    竖倾斜ScrollView
    本地资源_Asset
    小型自动朝向转盘
    简易C# socket
    Lua class
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4845443.html
Copyright © 2011-2022 走看看