[lintcode easy]Binary Tree Inorder Traversal

Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.

 
Given binary tree {1,#,2,3},
   1
    \
     2
    /
   3

 

return [1,3,2].

Challenge

Can you do it without recursion?

 

Inorder means that the order of traversal is Left child---parent---right child.

recursion version:

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
    * @return: Inorder in ArrayList which contains node values.
     */
        ArrayList<Integer> list=new ArrayList<Integer>();
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        // write your code here
        if(root!=null)
        {
            helper(root);
        }
        return list;
    }
    
    public void helper(TreeNode p)
    {
        if(p.left!=null)
        {
            helper(p.left);
        }
        list.add(p.val);
        if(p.right!=null)
        {
            helper(p.right);
        }
    }
}

 

Iteration version:

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
//Definition for binary tree
public class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode(int x) { val = x; }
 }
 
public class Solution {
    public ArrayList<Integer> inorderTraversal(TreeNode root) {

         ArrayList<Integer> list = new ArrayList<Integer>();
 
        if(root == null)
            return list; 
 
        Stack<TreeNode> stack = new Stack<TreeNode>();
        //define a pointer to track nodes
        TreeNode p = root;
 
        while(!stack.empty() || p != null){
 
            // if it is not null, push to stack
            //and go down the tree to left
            if(p != null){
                stack.push(p);
                p = p.left;
 
            // if no left child
            // pop stack, process the node
            // then let p point to the right
            }else{
                TreeNode t = stack.pop();
                lst.add(t.val);
                p = t.right;
            }
        }
 
        return list;
    }
}

 

posted on 2015-11-17 03:36  一心一念  阅读(225)  评论(0编辑  收藏  举报

导航