[LeetCode104]Maximum Depth of Binary Tree

来源:互联网 发布:松岗卓翼科技工资算法 编辑:程序博客网 时间:2024/04/28 17:20

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.

这道题我用的是递归,如果树的根节点为空,则返回0,否则返回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:    int maxDepth(TreeNode* root) {        if(root==NULL)        return 0;        else        {            int Ldepth=maxDepth(root->left)+1;            int Rdepth=maxDepth(root->right)+1;            return Ldepth>Rdepth?Ldepth:Rdepth;        }    }};


0 0
原创粉丝点击