- 二叉树的前、中、后序遍历
给你二叉树的根节点 root ,返回它节点值的 前序 遍历
示例:
输入:root = [1,null,2,3]
输出:[1,2,3]
前序遍历
代码1:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list= new ArrayList<>();
if(root!=null){
list.add(root.val);
List<Integer> leftList=preorderTraversal(root.left);
list.addAll(leftList);
List<Integer> rightList=preorderTraversal(root.right);
list.addAll(rightList);
}
return list;
}
}
代码2:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
preorder(root, list);
return list;
}
public void preorder(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
list.add(root.val);
preorder(root.left, list);
preorder(root.right, list);
}
}
中序遍历
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list= new ArrayList<>();
if(root!=null){
List<Integer> leftList=inorderTraversal(root.left);
list.addAll(leftList);
list.add(root.val);
List<Integer> rightList=inorderTraversal(root.right);
list.addAll(rightList);
}
return list;
}
}
后序遍历
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list= new ArrayList<>();
if(root!=null){
List<Integer> leftList=postorderTraversal(root.left);
list.addAll(leftList);
List<Integer> rightList=postorderTraversal(root.right);
list.addAll(rightList);
list.add(root.val);
}
return list;
}
}