您的位置:首页 > 其它

leetcode Maximum Depth of Binary Tree

2016-08-02 17:27 357 查看
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.

统计二叉树的最大深度,分为BFS,和DFS

BFS思路:

思路最重要,有了思路才有代码。

1.每次遍历一层,把这层所有的节点遍历完。

2.把这层所有的左右子树依次压入队列。

3.这层遍历完后,把这层所有的根节点pop出来。进入下一层节点,即步骤2中新压入的节点。

4.再遍历2中的所有节点,遍历完后,pop

/**
* 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 deepth=0;
if (root ==NULL)
return 0;

queue<TreeNode *> dequeTree;
dequeTree.push(root);

while(!dequeTree.empty()){
deepth++;

for(int i=0,n=dequeTree.size();i<n;i++){
TreeNode *p =dequeTree.front();
dequeTree.pop();

if(p->left!=NULL)
dequeTree.push(p->left);
if(p->right!=NULL)
dequeTree.push(p->right);
}
}

return deepth;

}
};

DFS 思路:

一直向下搜索,直到搜索到叶子时才返回。意味着每个分支都要被遍历和比较。

class Solution {
public:
int maxDepth(TreeNode* root) {
if (root ==NULL)
return 0;

return max(maxDepth(root->left),maxDepth(root->right))+1;

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