104. Maximum Depth of Binary Tree
仅供自己学习
思路:
用DFS递归即可,每次进入一个递归,就相当于下去一层,深度加1,再将深度传入即可。如果到叶子节点了,就返回深度,这个深度是左右两个子树在比较谁更深,去最深的长度作为返回的深度
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 int DFS(TreeNode* root,int level){ 15 if(!root) return level; 16 int l_l=level+1,r_l=level+1; 17 if(root->left)l_l=DFS(root->left,l_l); 18 if(root->right)r_l=DFS(root->right,r_l); 19 return max(r_l,l_l); 20 } 21 int maxDepth(TreeNode* root) { 22 int depth=DFS(root,0); 23 return depth; 24 } 25 };
还有更为简洁的DFS递归方法
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 int maxDepth(TreeNode* root) { 15 if(!root) return 0; 16 return max(maxDepth(root->left),maxDepth(root->right))+1; //每次返回的都是当前的层次,从最底开始从0计数 17 } 18 };
BFS,和一般的BFS相同,但是遍历一层的时候要一个变量存储他的节点数,否则将无法判断该层是否遍历完毕。每次遍历完一层,就计数一次。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 int maxDepth(TreeNode* root) { 15 if(!root) return 0; 16 int res=0; 17 queue<TreeNode*> q; 18 q.push(root); 19 while(!q.empty()){ 20 int n=q.size(); 21 while(n>0){ 22 auto temp=q.front();q.pop(); 23 if(temp->left) q.push(temp->left); 24 if(temp->right) q.push(temp->right); 25 n--; 26 } 27 res++; 28 } 29 return res; 30 } 31 };