[LeetCode]104. Maximum Depth of Binary Tree
题目描述
思路
深搜,节点为NULL返回0,其余比较左右子树大小,返回大值
代码
/**
* 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 maxDepth(TreeNode* root) {
if (!root)
return 0;
int left = 1 + maxDepth(root->left);
int right = 1 + maxDepth(root->right);
return left > right ? left : right;
}
};
本文介绍了一种使用深度优先搜索(DFS)算法来解决LeetCode上编号为104的问题——二叉树的最大深度。通过递归方式遍历二叉树的左子树和右子树,找到最大的深度并返回。此方法简洁高效。
430

被折叠的 条评论
为什么被折叠?



