public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
二叉树全序列(递归序)
private void totalOrderTraversal(TreeNode head){
if(head == null){
return;
}
System.out.print(head.val);
totalOrderTraversal(head.left);
System.out.print(head.val);
totalOrderTraversal(head.right);
System.out.print(head.val);
}
全序遍历结果
6 4 2 1 1 1 2 3 3 3 2 4 5 5 5 4 6 8 7 7 7 8 9 9 10 10 10 9 8 6
在整个全序遍历过程中 每个节点都会被遍历三次,
那么这个节点所有第一次出现就被称为先序遍历
第二次出现 就是中序遍历
最后一次出现就是后续遍历
二叉树先序遍历-递归
public static void preorderTraversal(TreeNode head){
if(head == null){
return;
}
System.out.print(" "+head.val);
preorderTraversal(head.left);
preorderTraversal(head.right);
}
6 4 2 1 3 5 8 7 9 10
二叉树中序遍历-递归
public static void mediumOrderTraversal(TreeNode head){
if(head == null){
return;
}
mediumOrderTraversal(head.left);
System.out.print(" "+head.val);
mediumOrderTraversal(head.right);
}
1 2 3 4 5 6 7 8 9 10
二叉树后序遍历-递归
public static void postorderTraversal(TreeNode head){
if(head == null){
return;
}
postorderTraversal(head.left);
postorderTraversal(head.right);
System.out.print(" "+head.val);
}
1 3 2 5 4 7 10 9 8 6
二叉树前序遍历-非递归实现
实现方法是使用栈先进后出的特性,
1、头结点压栈
2、弹出栈时打印
3、将弹出栈节点的右节点压栈,再将左节点压栈
4、重复2、3步骤知道栈为空
/**
* 先序遍历
* @param head
*/
public static void preorderTraversal2(TreeNode head) {
Stack<TreeNode> stack = new Stack<>();
stack.push(head);
while (!stack.isEmpty() & head != null) {
TreeNode currTreeNode = stack.pop();
System.out.print(currTreeNode.val);
if (currTreeNode.right != null) {
stack.push(currTreeNode.right);
}
if (currTreeNode.left != null) {
stack.push(currTreeNode.left);
}
}
}
二叉树中序遍历-非递归实现
1、先进当前节点所有的左节点压栈
2、在弹出栈时打印,并将节点执行其右节点
3、重复1、2直到栈为空
/**
* 中序遍历
* @param treeNode
*/
public static void mediumOrderTraversal2(TreeNode head){
Stack<TreeNode> stack = new Stack<>();
while (!stack.isEmpty() || head!=null){
if (head!=null){
stack.push(head);
head = head.left;
}else {
head = stack.pop();
System.out.print(head.val);
head = head.right;
}
}
}
二叉树后序遍历-非递归实现
1、先将头结点压入stack栈
2、从stack弹出一个节点currTreeNode
3、将currTreeNode压入postStack
4、如果currTreeNode的左节点不为null将左节点压入栈
5、如果currTreeNode的右节点不为null将右节点压入栈
6、循环2、3、4、5只带stack不为null
7、依次弹出postStack并打印
/**
* 后序遍历
* @param head
*/
public static void postorderTraversal2(TreeNode head){
Stack<TreeNode> stack = new Stack<>();
Stack<TreeNode> postStack = new Stack<>();
stack.push(head);
while (!stack.isEmpty() && head!=null){
TreeNode currTreeNode = stack.pop();
postStack.push(currTreeNode);
if (currTreeNode.left != null) {
stack.push(currTreeNode.left);
}
if (currTreeNode.right != null) {
stack.push(currTreeNode.right);
}
}
while (!postStack.isEmpty()){
System.out.print(postStack.pop().val);
}
}
左神老师讲的二叉树遍历,手动记录一下,简直不要太透彻了。