我们知道,一个二叉树的节点可以含有左右子结点
如root.left 和 root.right
整体思想:利用递归的方式进行
以前序为例 :
public void preOrder(){ System.out.println(this); //先输出父节点 //递归向左子树前序遍历 if (this.left != null){ this.left.preOrder(); } //递归向左子树前序遍历 if (this.right != null){ this.right.preOrder(); } }
不难看出前序 的输出方式为 “中左右”,先输出该节点,接着往左右两边递归的遍历。
再以力扣的 145. 二叉树的后序遍历
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
postorder(res,root);
return res;
}
//外部封装一个方法,递归的往 List里添加 数值
public void postorder(List<Integer> res,TreeNode root) {
if(root == null){
return;
}
if(root.left != null){
postorder(res,root.left);
}
if(root.right != null){
postorder(res,root.right);
}
res.add(root.val);
}
}
在外部封装的postorder方法中,我们先是递归的向左子树进行遍历添加,接着向右子树遍历添加,最后才是根节点。