题目描述:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
返回它的最大深度 3 。
方法1:递归
主要思路:
(1)正常的先序遍历递归处理;
/**
* 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:
void helper(TreeNode* root,int& cur_depth,int& max_depth){
//终止条件
if(root==NULL)
return ;
++cur_depth;//深度增加
//若是叶子结点,则更新可能的最大值
if(root->left==NULL&&root->right==NULL){
max_depth=max(max_depth,cur_depth);
}
//左右子树遍历
helper(root->left,cur_depth,max_depth);
helper(root->right,cur_depth,max_depth);
--cur_depth;//因为是引用,使用类似回溯,复原数值
}
int maxDepth(TreeNode* root) {
//处理特殊的情形
if(root==NULL)
return 0;
if(root->left==NULL&&root->right==NULL)
return 1;
//两个辅助变量,因为使用的是引用处理的
int max_depth=0;
int cur_depth=0;
//调用递归函数
helper(root,cur_depth,max_depth);
return max_depth;
}
};