您的位置:首页 > 其它

Binary Tree Inorder Traversal

2015-09-29 08:43 148 查看
(referrence: ProgramCreek)

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

The order of "inorder" is: left child -> parent -> right child

Use a stack to track nodes

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

public class Solution {
List<Integer> result = new ArrayList<Integer>();

public List<Integer> inorderTraversal(TreeNode root) {
if(root !=null){
helper(root);
}

return result;
}

public void helper(TreeNode p){
if(p.left!=null)
helper(p.left);

result.add(p.val);

if(p.right!=null)
helper(p.right);
}
}


Algorithm 2 -- Iterative

public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ArrayList<Integer> lst = new ArrayList<Integer>();

if(root == null)
return lst;

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 lst;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: