leetcode Maximum Depth of Binary Tree

来源:互联网 发布:pscs3软件百度云 编辑:程序博客网 时间:2024/06/08 05:57

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;            }};


0 0
原创粉丝点击