二叉树的前中后序遍历
对于二叉树的遍历来说,一般采用递归的方法即可。在写递归函数的时候,我们要知道,递归函数需要传入的参数以及返回值是什么?递归截至的条件是什么?每一次递归的逻辑是什么?
二叉树的前序:中左右
二叉树的中序:左中右
二叉树的后续:左右中
那么以前序举例,我们的递归函数,需要传入根节点,以及存放最后结果的list列表。当节点的值为空的时候,就证明这一层我们已经遍历完了。那么单层递归的逻辑就按照顺序来,先添加中,再添加左,右即可。(中的话直接往列表里添加节点的值list.add(root.val),左右节点preoder(root.left,list)/preoder(root.right,list)
// 前序遍历·递归·LC144_二叉树的前序遍历
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
preorder(root, result);
return result;
}
public void preorder(TreeNode root, List<Integer> result) {
if (root == null) {
return;
}
result.add(root.val);
preorder(root.left, result);
preorder(root.right, result);
}
}
// 中序遍历·递归·LC94_二叉树的中序遍历
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
inorder(root, res);
return res;
}
void inorder(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
inorder(root.left, list);
list.add(root.val); // 注意这一句
inorder(root.right, list);
}
}
// 后序遍历·递归·LC145_二叉树的后序遍历
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
postorder(root, res);
return res;
}
void postorder(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
postorder(root.left, list);
postorder(root.right, list);
list.add(root.val); // 注意这一句
}
}