https://leetcode.com/problems/maximum-depth-of-binary-tree/description/原題鏈接
原文:
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.
Example
Given a binary tree as follow:1 / \ 2 3 / \ 4 5
The maximum depth is 3.
翻譯:
給定一個二叉樹,找出其最大深度。
二叉樹的深度爲根節點到最遠葉子節點的距離。
給出一棵如下的二叉樹:
1 / \ 2 3 / \ 4 5
這個二叉樹的最大深度爲3.
解題思路:
使用深度優先搜索,遍歷二叉樹所有節點,找出最大深度,其中深度優先搜索,使用遞歸法,可以採取遞歸-遍歷法、遞歸-分治法來實現。代碼如下:
// 遞歸 - 遍歷法
public class Solution {
private int depth;
public int maxDepth(TreeNode root) {
depth = 0;
helper(root, 1);
return depth;
}
private void helper(TreeNode node, int curtDepth) {
if (node == null) {
return;
}
if (curtDepth > depth) {
depth = curtDepth;
}
helper(node.left, curtDepth + 1);
helper(node.right, curtDepth + 1);
}
}
// 遞歸 - 分治法
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
}