Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes‘ values.
{1,#,2,3}
,
1 2 / 3
return [1,3,2]
.
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:
//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; } }
[lintcode easy]Binary Tree Inorder Traversal
原文:http://www.cnblogs.com/kittyamin/p/4970592.html