Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
return 3
思路
求二叉樹的最大深度,簡單的分治法,左右子樹的最大深度加一即可
代碼
class Solution {
public int maxDepth(TreeNode root) {
// 邊界處理
if (root == null) {
return 0;
}
// 遞歸出口
if (root.left == null && root.right == null) {
return 1;
}
// Devide
int left = maxDepth(root.left);
int right = maxDepth(root.right);
//Merge
return Math.max(left, right) + 1;
}
}
traverse 方法
public class Solution {
private int depth;
public int maxDepth(TreeNode root) {
depth = 0;
traverse(root, 1);
return depth;
}
private void traverse(TreeNode root, int curDepth) {
if (root == null) {
return;
}
if (curDepth > depth) {
depth = curDepth;
}
traverse(root.left, curDepth + 1);
traverse(root.right, curDepth + 1);
}
}