LeetCode 104:Maximum Depth of Binary Tree

来源:互联网 发布:qq赚钱软件 编辑:程序博客网 时间:2024/05/16 23:58

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.

给定一颗二叉树,找到它的最大深度。

最大深度定义为从根节点到叶节点的最长路径。


思路其实挺简单。。。分别记录左右枝的最大值,返回较大的那一个即可

/** * 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) {        int max_left=1,max_right=1;        if(root==NULL) return 0;        else if(root->left==NULL&&root->right==NULL) return 1;        if(root->left!=NULL)            max_left=(1+maxDepth(root->left));         if(root->right!=NULL)            max_right=(1+maxDepth(root->right));        return max_left>max_right?max_left:max_right;    }};


0 0
原创粉丝点击