問題:
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.
大意:
給出一個二叉樹,找到其最大的深度。
最大深度是指從根節點到最遠的葉子節點的最長距離的節點數。
思路:
要探索二叉樹的深度,用遞歸比較方便。我們題目要求的函數返回根節點的深度,那么就做到對二叉樹上每個節點調用此函數都返回其作為根節點看待時的深度。比如,所有葉子節點的深度都是1,再往上就是2、3...一直到root根節點的返回值就是最大的深度。
對于每個節點,我們先判斷其本身是否是節點,如果是一個空二叉樹,那么就應該返回0。
然后,我們定義兩個變量,一個左節點深度,一個右節點深度。我們分別判斷其有無左節點和右節點,兩種節點中的做法都是一樣的,假設沒有左節點,那么就左節點深度變量就是1,有左節點的話,左節點深度變量就是對左節點調用此函數返回的結果加1;對右節點也做同樣的操作。
最后比較左節點深度和右節點深度,判斷誰比較大,就返回哪個變量。這樣就能一層一層地遞歸獲取最大深度了。
代碼(Java):
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if (root != null) {// 有此節點
int rightResult;
int leftResult;
if (root.left != null) {// 有左節點
leftResult = maxDepth(root.left) + 1;
} else {// 無左節點
leftResult = 1;
}
if (root.right != null) {// 有右節點
rightResult = maxDepth(root.right) + 1;
} else {// 無右節點
rightResult = 1;
}
// 判斷哪邊更深,返回更深的深度
return leftResult > rightResult ? leftResult : rightResult;
} else {// 無此節點,返回0
return 0;
}
}
}
不過我們稍加思考一下,就可以進一步簡略一下代碼。因為我們代碼里對于root為null的情況下返回的是0,那其實沒有左節點時,對齊使用函數返回的也會是0,加1的話就是我們需要的1了,所以其實不用判斷有無左節點,右節點也是一樣。所以可以簡化如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if (root != null) {
int rightResult = maxDepth(root.left) + 1;
int leftResult = maxDepth(root.right) + 1;
return leftResult > rightResult ? leftResult : rightResult;
} else {
return 0;
}
}
}
也可以額外寫個函數,在參數里傳遞深度。
// C++:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int depth(TreeNode* node, int level) {
if (node == NULL) return level-1;
int left = depth(node->left, level+1);
int right = depth(node->right, level+1);
return max(left, right);
}
int maxDepth(TreeNode* root) {
return depth(root, 1);
}
};
合集:https://github.com/Cloudox/LeetCode-Record