![](https://img-blog.csdnimg.cn/direct/1360803e860949d9a77999e1e4eee3b7.png)
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root==null) return result;
Deque<TreeNode> dq = new LinkedList<>();
dq.add(root);
while(!dq.isEmpty()){
int size = dq.size();
List<Integer> path = new ArrayList<>();
for(int i=0;i<size;i++){
TreeNode node = dq.poll();
path.add(node.val);
if (node.left!=null) dq.add(node.left);
if (node.right!=null) dq.add(node.right);
}
result.add(path);
}
return result;
}
}
![](https://img-blog.csdnimg.cn/direct/9f4d0090054e4bb288271b79da0fa642.png)
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return sort(nums,0,nums.length-1);
}
public TreeNode sort(int[] nums, int left, int right){
if (left>right) return null;
int mid = (left+right)>>1;
TreeNode root = new TreeNode(nums[mid]);
root.left = sort(nums,left,mid-1);
root.right = sort(nums,mid+1,right);
return root;
}
}
![](https://img-blog.csdnimg.cn/direct/69bc4749b54e4f33b381919581b0cc67.png)
class Solution {
public boolean isValidBST(TreeNode root) {
// 使用Long是因为存在integer的最大值不够用,有例子:value=2147483647
return isValid(root,Long.MIN_VALUE,Long.MAX_VALUE);
}
public boolean isValid(TreeNode root, long min, long max){
if (root==null) return true;
if (root.val<=min || root.val>=max) {
return false;
}
boolean left = isValid(root.left,min,root.val);
boolean right = isValid(root.right,root.val,max);
return left && right;
}
}
![](https://img-blog.csdnimg.cn/direct/17c7d3a267d949719d7633f6494647d0.png)
class Solution {
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> que = new Stack<TreeNode>();
if (root==null) return -1;
while(root!=null || !que.isEmpty()){
while(root!=null){
que.push(root);
root = root.left;
}
root = que.pop();
--k;
if (k==0) break;
root = root.right;
}
return root.val;
}
}
![](https://img-blog.csdnimg.cn/direct/ed00552599c1431ea4d21f154aa10283.png)
class Solution {
List<Integer> result;
public List<Integer> rightSideView(TreeNode root) {
result = new LinkedList<>();
if (root==null) return result;
findright(root);
return result;
}
private void findright(TreeNode root){
Queue<TreeNode> que = new LinkedList<TreeNode>();
que.add(root);
while(!que.isEmpty()){
int size = que.size();
for (int i=0;i<size;i++){
TreeNode node = que.poll();
if (node.left!=null) que.add(node.left);
if (node.right!=null) que.add(node.right);
if (i==size-1) result.add(node.val);
}
}
}
}
class Solution {
List<Integer> reslut;
public List<Integer> rightSideView(TreeNode root) {
reslut = new ArrayList<>();
if(root==null) return reslut;
dfs(root,0);
return reslut;
}
private void dfs(TreeNode root, int depth){
if (root==null) return;
if (depth==reslut.size()){
reslut.add(root.val);
}
depth++;
dfs(root.right,depth);
dfs(root.left,depth);
}
}