您的位置:首页 > 其它

104. Maximum Depth of Binary Tree

2016-04-19 10:31 363 查看
104. Maximum Depth of Binary Tree

容易想到两种思路,深度优先搜索(DFS)和广度优先搜索(BFS):

思路一(DFS):

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)//1.递归结束条件
return 0;
int l=maxDepth(root->left);//2.左子树深度
int r=maxDepth(root->right);//2.右子树深度
return l>r?l:r;//3.递归操作

}
};


思路二(BFS):

struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
int maxDepth(TreeNode* root) {
queue< TreeNode * > que;//引入队列
que.push(root);
int num=1;//记录每一层的节点数
int depth=0;//记录树的深度

while(!que.empty())
{
TreeNode* node=que.front();
que.pop();
num--;
if(node->left!=NULL)
que.push(node->left);
if(node->right!=NULL)
que.push(node->right);
if(num==0)//一层遍历结束
{
depth++;
num=que.size();
}
}
return depth;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: