题解 | #二叉树根节点到叶子节点的所有路径和#

二叉树的最大深度

http://www.nowcoder.com/practice/8a2b2bf6c19b4f23a9bdb9b233eefa73

注意要回溯两次 根节点和每一个节点被搜完后

 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    int ans = 0;
    int cnt = 0;
    void dfs(TreeNode* root){
        if(root->left == NULL && root->right == NULL){
            cnt++;
            ans = max(cnt,ans);
            cnt--;
            return;
        }
        cnt++;
        if(root->left != NULL) dfs(root->left);
        if(root->right != NULL) dfs(root->right);
        cnt--;
        
    }
    int maxDepth(TreeNode* root) {
        if(root == NULL) return 0;
        dfs(root);
        return ans;
    }
};
全部评论

相关推荐

只写bug的程序媛:人家说一本以上,不是及以上
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务