LinkedList<Integer> list = new LinkedList<>();
public List<Integer> inorderTraversal(TreeNode root) {
traverse(root);
return list;
}
private void traverse(TreeNode root) {
if (root == null){
return;
}
traverse(root.left);
list.add(root.val);
traverse(root.right);
}
public List<TreeNode> generateTrees(int n) {
if (n == 0){
return new LinkedList<>();
}
return build(1,n);
}
private List<TreeNode> build(int lo, int hi) {
List<TreeNode> list = new LinkedList<>();
if (lo > hi){
list.add(null);
return list;
}
//穷尽root节点所有可能节点
for (int i = lo; i <= hi; i++){
List<TreeNode> leftTree = build(lo,i-1);
List<TreeNode> rightTree = build(i+1,hi);
for (TreeNode left : leftTree){
for (TreeNode right : rightTree){
TreeNode root = new TreeNode(i);
root.left = left;
root.right = right;
list.add(root);
}
}
}
return list;
}
int[][] memo;
int numTrees(int n){
memo = new int[n+1][n+1];
return count(1,n);
}
private int count(int lo, int hi) {
if (lo > hi){
return 1;
}
if (memo[lo][hi] != 0){
return memo[lo][hi];
}
int res = 0;
for (int i = lo; i <= hi; i++){
int left = count(lo,i-1);
int right = count(i+1,hi);
res += left*right;
}
memo[lo][hi] = res;
return res;
}
public boolean isValidBST(TreeNode root) {
return isValidBST(root, null, null);
}
/* 限定以 root 为根的子树节点必须满足 max.val > root.val > min.val */
boolean isValidBST(TreeNode root, TreeNode min, TreeNode max) {
if (root == null){
return true;
}
if (min != null && root.val <= min.val){
return false;
}
if (max != null && root.val >= max.val){
return false;
}
return isValidBST(root.left,min,root) && isValidBST(root.right,root,max);
}
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q != null || p != null && q == null){
return false;
}
if (p == null && q == null){
return true;
}