二叉树的前中后序遍历
关于二叉树的遍历,常见的有三种遍历方式,即,前序遍历,中序遍历,后序遍历,这个‘序’字,即指当前的节点对于其左右子节点的先后处理关系。
前序遍历
结合我们刚刚讲的,就知道对于其左右子树而言,优先遍历当前的父节点,然后遍历它的左子树,最后遍历它的右子树。
中序遍历
对于其左右子树而言,当前父节点在中间遍历,即先遍历当前节点的左子树,然后遍历它本身,再遍历右子树。
后序遍历
对于其左右子树而言,先遍历左子树,再遍历右子树,最后遍历父节点。
代码实现
二叉树的遍历显然也可以通过递归的方式。
//前序遍历
void preNode(TreeNode root){
if (root == null){
return;
}
System.println(root.val);
preNode(list,root.left);
preNode(list,root.right);
}
//中序遍历
void inNode(TreeNode root){
if (root == null){
return;
}
inNode(list,root.left);
System.println(root.val);
inNode(list,root.right);
}
//后序遍历
void postNode(TreeNode root){
if (root == null){
return;
}
postNode(list,root.left);
postNode(list,root.right);
System.println(root.val);
}