二叉树的遍历
采用List将遍历的值保存
1.前序遍历
题目
代码示例
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<Integer>();
preorder(list, root);
return list;
}
public static void preorder(List<Integer> list,TreeNode root){
if(root!=null){
list.add(root.val);
preorder(list, root.left);
preorder(list, root.right);
}
}
}
2.中序遍历
题目
代码示例
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<Integer>();
inorder(list, root);
return list;
}
public static void inorder(List<Integer> list,TreeNode root){
if(root!=null){
inorder(list, root.left);
list.add(root.val);
inorder(list, root.right);
}
}
}
3.后序遍历
题目
代码示例
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<Integer>();
postorder(list, root);
return list;
}
public static void postorder(List<Integer> list,TreeNode root){
if(root!=null){
postorder(list, root.left);
postorder(list, root.right);
list.add(root.val);
}
}
}