104. Maximum Depth of Binary Tree
java
class Solution {
public int maxDepth(TreeNode root) {
if (root == null){
return 0;
}
int left = maxDepth(root.left); //左
int right = maxDepth(root.right); //右
return 1 + Math.max(left, right); //中
}
}
java
class Solution {
public int maxDepth(TreeNode root) {
int res = 0;
if (root == null){
return 0;
}
Queue queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
int size = queue.size();
res++;
while(size > 0){
TreeNode temp = queue.poll();
if(temp.left != null){
queue.add(temp.left);
}
if(temp.right != null){
queue.add(temp.right);
}
size--;
}
}
return res;
}
}
559. Maximum Depth of N-ary Tree
java
class Solution {
public int maxDepth(Node root) {
if (root == null){
return 0;
}
int depth = 0;
//卡哥题解里这里有个判断children != null 的剪枝我给去掉了,为了对齐104的做法,初学者变化不需要太多
for(Node child : root.children){
depth = Math.max(depth, maxDepth(child));
}
return depth +1;
}
}
java
class Solution {
public int maxDepth(Node root) {
if (root == null){
return 0;
}
int depth = 0;
Queue que = new LinkedList<>();
que.add(root);
while( !que.isEmpty()){
int size = que.size();
depth++;
while(size > 0 ){
Node temp = que.poll();
for( Node child : temp.children){
if(child != null){
que.add(child);
}
}
size--;
}
}
return depth;
}
}
111. Minimum Depth of Binary Tree
java
class Solution {
public int minDepth(TreeNode root) {
if (root == null){
return 0;
}
int left = minDepth(root.left);
int right = minDepth(root.right);
if (root.left == null && root.right != null){
return 1 + right;
}
if (root.right == null && root.left != null){
return 1 + left;
}
return 1 + Math.min(left, right);
}
}
javascript
class Solution {
public int minDepth(TreeNode root) {
int res = 0;
if (root == null){
return 0;
}
Queue queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
int size = queue.size();
res++;
while( size > 0){
TreeNode temp = queue.poll();
//只要遍历到叶子节点就可以直接return
if(temp.left == null && temp.right == null){
return res;
}
if (temp.left != null){
queue.add(temp.left);
}
if (temp.right != null){
queue.add(temp.right);
}
size--;
}
}
return res;
}
}
222. Count Complete Tree Nodes
java
class Solution {
public int countNodes(TreeNode root) {
if (root == null){
return 0;
}
//以下是判断满二叉树的停止的情况
int left = 0;
int right = 0;
TreeNode curLeft = root.left;
TreeNode curRight = root.right;
while(curLeft != null){
curLeft = curLeft.left;
left++;
}
while(curRight != null){
curRight = curRight.right;
right++;
}
if (left == right){
return (2