力扣-104-二叉树的最大深度
题目分析:
方法一:递归
求解根节点的最大深度,可以转化为根节点的深度$1$,加上左子树和右子树的最大深度中较大的那一个。通过分析,这明显是一个递归问题,用递归求解代码也比较简单。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include <algorithm> using namespace std; class Solution { public: int maxDepth(TreeNode* root) { if (root == NULL) return 0; return max(maxDepth(root->left), maxDepth(root->right)) + 1; } };
方法二:$bfs$
求解树的最大深度,实际上可以通过bfs进行层次遍历,然后每遍历一层,$result$加一,$bfs$实现二叉树的层序遍历同上题。
/*二叉树求树的最大深度使用bfs*/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include <queue> #include <vector> using namespace std; class Solution { public: int maxDepth(TreeNode* root) { int result = 0; queue<TreeNode*> tree; if (root!= NULL) tree.push(root); while(!tree.empty()){ int num = tree.size(); for(int i = 0; i < num; i++){ TreeNode* node = tree.front(); tree.pop(); if(node->left != NULL) tree.push(node->left); if(node->right != NULL) tree.push(node->right); } result += 1; } return result; } };
作者:Ryanjie
出处:http://www.cnblogs.com/ryanjan/
本文版权归作者和博客园所有,欢迎转载。转载请在留言板处留言给我,且在文章标明原文链接,谢谢!
如果您觉得本篇博文对您有所收获,觉得我还算用心,请点击右下角的 [推荐],谢谢!