题目列表
LeetCode节点格式
Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
1. 二叉树的前序遍历。
import java.util.ArrayList;
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
bianli(list,root);
return list;
}
public static void bianli(List<Integer> list,TreeNode root){
if(root == null){
return;
}
list.add(root.val);
bianli(list,root.left);
bianli(list,root.right);
}
}
2. 二叉树中序遍历 。
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
zhongxv(list,root);
return list;
}
public static void zhongxv(List<Integer> list,TreeNode root){
if(root == null){
return;
}
zhongxv(list,root.left);
list.add(root.val);
zhongxv(list,root.right);
}