98.验证二叉搜索树(中序遍历)
class Solution {
long pre = Long.MIN_VALUE;
public boolean isValidBST(TreeNode root) {
if(root == null) return true;
if(!isValidBST(root.left)) return false;
if(pre >= root.val) return false;
pre = root.val;
if(!isValidBST(root.right)) return false;
return true;
}
}
102.二叉树的层序遍历(递归(dfs)+迭代(bfs))
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
dfs(root, 0, res);
return res;
}
public void dfs(TreeNode root, int index, List<List<Integer>> res) {
if(root == null) return;
if(res.size() < index + 1) res.add(new ArrayList<>());
res.get(index).add(root.val);
dfs(root.left, index + 1, res);
dfs(root.right, index + 1, res);
}
}
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()) {
int size = queue.size();
List<Integer> temp = new ArrayList<>();
for(int i = 0; i < size; i++) {
TreeNode t = queue.remove();
temp.add(t.val);
if(t.left != null) queue.add(t,left);
if(t.right != null) queue.add(t.right);
}
res.add(temp);
}
return res;
}
}