使用递归 public class Solution {
public int run(TreeNode root) {
if(root==null){
return 0;
}
if(root.left==null&&root.right==null){
return 1;
}
if(root.left==null || root.right==null){
return Math.max(run(root.left),run(root.right))+1;
}
return Math.min(run(root.left),run(root.right))+1;
}
}
不使用递归 import java.util.*;
public class Solution {
public int run(TreeNode root) {
if(root==null){
return 0;
}
if(root.left==null&&root.right==null){
return 1;
}
Queue queue = new LinkedList();
queue.add(root);
int level = 1;
while(!queue.isEmpty()){
int size = queue.size();
for(int i=0;i
TreeNode node = queue.poll();
if(node.left==null&&node.right==null){
return level;
}
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
level++;
}
return level;
}
}
总结 二叉树操作主要还是利用尾递归或者循环遍历这两种思路,进而涉及DFS(主要利用递归或者栈实现)或者BFS(主要利用队列实现)。剩下的只需要按照这些思路即可。