有关深度的题:
DFS递归:
时间复杂度:O(N)
空间复杂度:最坏O(N)(斜二叉树),最好O(logN)(完全二叉树)
class Solution {
public int maxDepth(TreeNode root) {
return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right))+ 1;
}
}
DFS递归
class Solution {
public int minDepth(TreeNode root) {
if (root == null)
return 0;
if ((root.left == null) && (root.right == null))
return 1;
int min_depth = Integer.MAX_VALUE;
if (root.left != null)
min_depth = Math.min(minDepth(root.left), min_depth);
if (root.right != null)
min_depth = Math.min(minDepth(root.right), min_depth);
return min_depth + 1;
}
}
BFS
class Solution {
public int minDepth(TreeNode root) {
int res = 0;
Queue<TreeNode> qu = new LinkedList<>();
if (root == null)
return 0;
qu.offer(root);
while (!qu.isEmpty()) {
res++;
int size = qu.size();
for (int i = 0; i < size; i++) {
TreeNode cur = qu.poll();
if (cur.left != null)
qu.offer(cur.left);
if (cur.right != null)
qu.offer(cur.right);
if (cur.left == null && cur.right == null) // 如果没有子树,返回最小深度
return res;
}
}
return res;
}
}
还是DFS
class Solution {
public int maxDepth(Node root) {
if(root == null)
return 0;
if(root.children.size() == 0)
return 1;
int Max = Integer.MIN_VALUE;
for(Node children : root.children){
Max = Math.max(maxDepth(children), Max);
}
return Max + 1;
}
}
判断是不是平衡二叉树,其实还是计算深度,当任何一个节点的左右子树深度之差的绝对值大于1的时候,这颗树就不是平衡二叉树,重用了第一道题的代码。
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) //空树应该也算平衡树吧...
return true;
if(Math.abs(maxDepth(root.left) - maxDepth(root.right)) > 1)
return false;
return isBalanced(root.left) && isBalanced(root.right);
}
public int maxDepth(TreeNode root) {
return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right))+ 1;
}
}