1、递归版
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;
}
}
2、非递归
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;
LinkedList<TreeNode> queue=new LinkedList<>();
queue.add(root);
int count=0;
while(!queue.isEmpty()){
int len=queue.size();
count++;
for(int i=0; i<len; i++){
TreeNode temp=queue.remove(0);
if(temp.left==null&&temp.right==null)
return count;
if(temp.left!=null)
queue.add(temp.left);
if(temp.right!=null)
queue.add(temp.right);
}
}
return count;
}
}