前中后序遍历的知识
1、前序遍历:先遍历根节点,再按照根-左-右的顺序遍历根节点的左子树,最后按照根-左-右的顺序遍历根节点的右子树。
2、中序遍历:先遍历根节点的左子树,按照左-根-右的顺序遍历完之后再遍历根节点,最后按照左-根-右的顺序遍历根节点的右子树。
3、后序遍历:先遍历根节点的左子树,按照左-右-根的顺序遍历完左子树后,再按照左-右-根的顺序遍历根节点的右子树,最后遍历根节点。
前中后序遍历树的非递归算法模板
前序遍历
public static void preOrder(TreeNode head){
if (head!=null){
Stack<TreeNode> stack=new Stack<>();
stack.push(head);
while (!stack.isEmpty()){
head=stack.pop();
//dosomething();
//System.out.println(head.val+" ");
if (head.right!=null){
stack.push(head.right);
}
if (head.left!=null){
stack.push(head.left);
}
}
}
}
使用栈来实现,先入根结点,然后排出,将根节点的右子树先入,再入左子树。
中序遍历
public static void inOrder(TreeNode head){
if (head!=null){
Stack<TreeNode> stack=new Stack<>();
while (!stack.isEmpty()||head!=null){
if (head!=null){
stack.push(head);
head=head.left;
}else {
head=stack.pop();
//dosomething();
//System.out.println(head.val+" ");
head=head.right;
}
}
}
}
使用栈来实现,先入根节点,再入根节点的左子树,当左子树到达叶子节点时,弹出叶子节点,往其父节点的右子树继续遍历。直到左子树全部遍历完进行右子树的遍历。
后序遍历
public static void posOrder(TreeNode head){
if (head!=null){
Stack<TreeNode> stack1=new Stack<>();
Stack<TreeNode> stack2=new Stack<>();
stack1.push(head);
while (!stack1.isEmpty()){
head=stack1.pop();
stack2.push(head);
if (head.left!=null){
stack1.push(head.left);
}
if (head.right!=null){
stack1.push(head.right);
}
}
while (!stack2.isEmpty()){
//dosomething();
//System.out.println(stack2.pop().val+" ");
}
}
}
后序遍历使用两个栈来实现,一个用来遍历,一个用来输出。
具体遇到需要用到前中后序遍历时需要根据需求调整代码。