題目: LeetCode - 104. Maximum Depth of Binary Tree

題目說明

給一個 Tree,找出它的最深深度。

解題思路

利用遞迴的概念,每個節點的最深深度為 左邊node 的最深深度 + 1 或是 右邊 node 的最深深度 + 1,終止條件為 root == nullptr 的時候。

參考解法

1
2
3
4
5
6
7
8
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root)
return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};