DFS 根节点的深度=max(左叶子深度,右叶子深度)+1
class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
}
BFS
class Solution {
public int maxDepth(TreeNode root) {
if(root ==null) return 0;
int res=0;
List<TreeNode> queue = new LinkedList<>(){{add(root);}},tmp;
while(!queue.isEmpty()){
tmp = new LinkedList<TreeNode>();
for(TreeNode node:queue){
if(node.left!=null) tmp.add(node.left);
if(node.right!=null)tmp.add(node.right);
}
res++;
queue = tmp;
}
return res;
}
}
后序遍历 + 剪枝 从底至顶
class Solution {
public boolean isBalanced(TreeNode root) {
return recur(root) != -1;
}
public int recur(TreeNode root){
if(root == null) return 0;
int left = recur(root.left);
if(left == -1) return -1;
int right = recur(root.right);
if(right == -1) return -1;
return Math.abs(left-right)<2 ? Math.max(left,right)+1 :-1;
}
}
|