参考自https://my.oschina.net/u/2248183/blog/1805341
先看一段代码:
public void inorderTraversal(TreeNode root) {
LinkedList<TreeNode> stack = new LinkedList<>();
if(root == null)
return ;
stack.push(root);
while(!stack.isEmpty()){
root = stack.pop();
if(root.left == null && root.right == null){
visit(root);
continue;
}
if(root.right != null)
stack.push(root.right);
stack.push(root);
if(root.left != null)
stack.push(root.left);
root.left = null;
root.right = null;
}
}
只要改变左、中、右节点压入堆栈的顺序即可实现前序和中序遍历
- 前序遍历(先右再左最后中)
public void preorderTraversal(TreeNode root) {
LinkedList<TreeNode> stack = new LinkedList<>();
if(root == null)
return ;
stack.push(root);
while(!stack.isEmpty()){
root = stack.pop();
if(root.left == null && root.right == null){
visit(root);
continue;
}
if(root.right != null)
stack.push(root.right);
if(root.left != null)
stack.push(root.left);
stack.push(root);
root.left = null;
root.right = null;
}
}
- 后序遍历:(先中再右最后左)
public void postorderTraversal(TreeNode root) {
LinkedList<TreeNode> stack = new LinkedList<>();
if(root == null)
return ;
stack.push(root);
while(!stack.isEmpty()){
root = stack.pop();
if(root.left == null && root.right == null){
visit(root);
continue;
}
stack.push(root);
if(root.right != null)
stack.push(root.right);
if(root.left != null)
stack.push(root.left);
root.left = null;
root.right = null;
}
}
这段代码应该最接近前中后序遍历的实质——在第n次经过节点时访问(n=1,2,3)