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 }
  • 相关阅读:
    状态压缩DP 不断学习中。。。。。。
    程序员技术练级攻略(转)
    SQL Server 2008安装提示1608错误的解决方法
    Delphi字符串指针操作
    一个Python练习
    Android开发中的svn问题
    Python使用正则表达式替换源码前序号
    百度地图之Hello world !
    用Python写的一个简单的端口扫描程序
    android地图定位
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4845443.html
Copyright © 2011-2022 走看看