博文中会简要介绍Leetcode P0104题目分析及解题思路。
“Maximum Depth of Binary Tree”是一道比较基础的树问题,可以借助深度优先搜索的思想,使用递归回溯的方法,每到一个树结点询问左右子树的高度,然后向下询问直到最底层,最终返回其中的大值并加上自身,即加上的高度为1。
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.
以下是Java的题解代码实现。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
return this.traverse(root);
}
private int traverse(TreeNode curr) {
if (curr == null)
return 0;
return Math.max(this.traverse(curr.right), this.traverse(curr.left))+1;
}
}
以下是C++的题解代码实现。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
return this->Traverse(root);
}
private:
int Traverse(TreeNode *curr) {
if (curr == NULL)
return 0;
return max(this->Traverse(curr->right), this->Traverse(curr->left))+1;
}
};