Given the root of a binary tree, return its maximum depth.
A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2:
Input: root = [1,null,2]
Output: 2
Constraints:
- The number of nodes in the tree is in the range [0, 104].
- -100 <= Node.val <= 100
Java completion:
class Solution {
/**
* 借助List嵌套计算二叉树的深度
*
* @param root
* @return
*/
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
List<List<TreeNode>> nodeList = new ArrayList<>();
nodeList.add(Arrays.asList((root)));
while (true) {
List<TreeNode> father = nodeList.get(nodeList.size() - 1);
List<TreeNode> child = new ArrayList<>();
for (TreeNode f : father) {
if (f.left != null) child.add(f.left);
if (f.right != null) child.add(f.right);
}
if (child.size() == 0) break;
nodeList.add(child);
}
return nodeList.size();
}
}
class Solution {
/**
* 借助栈计算二叉树的深度
*
* @param root
* @return
*/
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
Stack<TreeNode> stack1 = new Stack<>();
stack1.push(root);
int depth = 0;
while (!stack1.isEmpty()) {
depth += 1;
Stack<TreeNode> stack2 = new Stack<>();
while (!stack1.isEmpty()) {
TreeNode f = stack1.pop();
if (f.left != null) stack2.push(f.left);
if (f.right != null) stack2.push(f.right);
}
stack1 = stack2;
}
return depth;
}
}
class Solution {
/**
* 递归计算二叉树的深度
*
* @param root
* @return
*/
public int maxDepth(TreeNode root) {
if (root == null) return 0;
int depth;
if (root.left != null && root.right != null) {
int lDepth = maxDepth(root.left) + 1;
int rDepth = maxDepth(root.right) + 1;
depth = lDepth > rDepth ? lDepth : rDepth;
} else if (root.left != null) {
depth = maxDepth(root.left) + 1;
} else if (root.right != null) {
depth = maxDepth(root.right) + 1;
} else {
depth = 1;
}
return depth;
}
}
class Solution {
/**
* 递归计算二叉树深度--代码优化版
* @param root
* @return
*/
public int maxDepth(TreeNode root) {
if (root == null) return 0;
int lDepth = maxDepth(root.left) + 1;
int rDepth = maxDepth(root.right) + 1;
return lDepth > rDepth ? lDepth : rDepth;
}
}