二叉树的最大深度(LeetCode104)
先表示左树的深度,再表示右树的深度。再进行条件判断
class solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
}
二叉树的最小深度(LeetCode111)
先表示左树的深度,再表示右树的深度。再进行条件判断。这里的条件就是:左右分别为空该怎么样返回。
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = minDepth(root.left);
int rightDepth = minDepth(root.right);
if (root.left == null) return rightDepth + 1;
if (root.right == null) return leftDepth + 1;
return Math.min(leftDepth, rightDepth) + 1;
}
}
二叉树的直径(LeetCode543)
先表示左树的深度,再表示右树的深度。再进行条件判断。左的深度+右的深度
class Solution {
int ans=0;
public int diameterOfBinaryTree(TreeNode root) {
depth(root);
return ans;
}
public int depth(TreeNode node) {
if (node == null) {
return 0;
}
int L = depth(node.left);
int R = depth(node.right);
ans = Math.max(ans, L+R);
return Math.max(L, R) + 1;
}
}
想必你也看出来了,代码都大同小异。
平衡二叉树(LeetCode110)
class Solution {
private boolean isBalanced;
public boolean isBalanced(TreeNode root) {
isBalanced = true;
dfs(root);
return isBalanced;
}
private int dfs(TreeNode root) {
if (root == null) {
return 0;
}
int lefDepth = dfs(root.left);
int rightDepth = dfs(root.right);
if (Math.abs(lefDepth-rightDepth) > 1) {
isBalanced = false;
}
return Math.max(lefDepth,rightDepth) + 1;
}
}