Inorder:
LinkedList<>stack=..
while ( root != null || !stack.isEmpty())
{
if ( root != null )
{
stack.push(root);
root = root.left;
}
else // root ==null
{
root= stack.pop();
res.add(root.val);
root= root.right;
}
}
|
Preorder:
LinkedList<>stack=..
while (root!= null || !stack.isEmpty())
{
if (root!= null)
{
stack.push(root);
res.add(root.val);
root =root.left;
}
else // root == null
{
root = stack.pop();
root = root.right;
}
}
|
Postorder:
LinkedList<>stack=...
TreeNode pre = new TreeNode();
while (root != null || !stack.isEmpty())
{
if (root!= null)
{
stack.push(root);
root = root.left;
}
else // root ==null
{
TreeNode peekNode = stack.peek();
//while (peekNode.right != null && peekNode.right != pre)
//peekNode.right == null;
if ( peekNode.right != null && pre != peekNode.right)
{
root = peekNode.right;
}
else { //peekNode.right ==null
stack.pop();
res.add(pre.val);
//root = pre.right;
pre = peekNode;
}
}
}
2. pre!= peekNode.right, already traverse right children, traverse me parent(root) now
|
Wednesday, September 9, 2015
[Tree] Tree Traversal Iterative Method
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment