简单深度优先
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例: 给定二叉树 [3,9,20,null,null,15,7], 3
/ \
9 20
/ \
15 7 最大深度就是3
递归解法
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/class Solution {public:int maxDepth(TreeNode* root) {if(root == nullptr) return 0;return max(maxDepth(root->left),maxDepth(root->right)) + 1;}};
这里需要注意的是max函数的返回值是个左值,不能直接++然后返回。
时间复杂度O(n)
空间复杂度O(height) 递归函数需要栈空间,而栈空间取决于递归的深度,因此空间复杂度等价于二叉树的高度。
BFS
class Solution {public:int maxDepth(TreeNode* root) {if(root == nullptr) return 0;queue<TreeNode*> q;q.push(root);int count = 0;while(!q.empty()){count++;int size = q.size();for(int i=0;i<size;i++){TreeNode* node = q.front();q.pop();if(node->left != nullptr){q.push(node->left);}if(node->right != nullptr){q.push(node->right);}}}return count;}};
改装一下BFS算法,让每次遍历的时候遍历一层就好。
