Easy 104题 Maximum Depth of Binary Tree

来源:互联网 发布:node express restful 编辑:程序博客网 时间:2024/06/05 01:04

问题: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.

又是一道有思路的题,直接写出答案,但是由于太不考虑复杂度了,报了time limited的错,改一下就好,但同样不是最优美的代码,看了discuss,发现有一行解决的!

以下这个代码的思路是DFS的,深度遍历。。。

/** * 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;        else        {            //return maxDepth(root->left)>maxDepth(root->right)?maxDepth(root->left)+1:maxDepth(root->right)+1; //算了多少遍。。复杂度太差            int l=maxDepth(root->left);            int r=maxDepth(root->right);            return l>r?l+1:r+1;            //return 1 + max(maxDepth(root->left), maxDepth(root->right)); //一行解决        }    }};

很自然想到应该还有BFS算法,引入队列?队列核心:first in first out 但是基本功太差。。啊先睡觉明儿早补

http://blueve.me/archives/417 这篇让我入门了。。

BFS复杂度更好些,因为没有递归。

/** * 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) {    //BFS    if(!root) return 0;    queue<TreeNode*> q;    q.push(root);    int count=1; //记录当前层数有多少元素    int depth=0;    while(!q.empty())    {        TreeNode* tmp=q.front();        q.pop(); //一一弹出当前层的元素        count--;         if(tmp->left)            q.push(tmp->left);        if(tmp->right)            q.push(tmp->right);        if(count==0)        {            depth++;            count=q.size();        }    }    return depth;    }};



0 0
原创粉丝点击