104. Maximum Depth of Binary Tree

来源:互联网 发布:淘宝为什么分数低 编辑:程序博客网 时间:2024/05/21 21:43

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+1):(r+1);//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;    }};
0 0
原创粉丝点击