104. 二叉树的最大深度
迭代法:
1 class Solution { 2 public: 3 int maxDepth(TreeNode* root) { 4 //创建变量用于存储深度 5 int ans = 0; 6 queue<TreeNode*> que; 7 if (root != nullptr) que.push(root); 8 while (!que.empty()){ 9 int size = que.size(); 10 while (size--){ 11 TreeNode* node = que.front(); 12 que.pop(); 13 if (node->left) que.push(node->left); 14 if (node->right) que.push(node->right); 15 } 16 ans++; 17 } 18 return ans; 19 } 20 };
递归法:
1 class Solution { 2 public: 3 int getdepth(TreeNode* node){ 4 if (node == nullptr) return 0; 5 int leftdepth = getdepth(node->left); 6 int rightdepth = getdepth(node->right); 7 int depth = 1 + max(leftdepth, rightdepth); 8 return depth; 9 } 10 11 int minDepth(TreeNode* root) { 12 return getdepth(root); 13 } 14 };
1 class Solution { 2 public: 3 int minDepth(TreeNode* root) { 4 int result = 0; 5 queue<TreeNode*> que; 6 if (root != nullptr) que.push(root); 7 while (!que.empty()){ 8 int size = que.size(); 9 result++; 10 while (size--){ 11 TreeNode* node = que.front(); 12 que.pop(); 13 if (node->left == nullptr && node->right == nullptr){ 14 return result; 15 } 16 if (node->left) que.push(node->left); 17 if (node->right) que.push(node->right); 18 } 19 } 20 return result; 21 } 22 };
222. 完全二叉树的节点个数
1 class Solution { 2 public: 3 int countNodes(TreeNode* root) { 4 queue<TreeNode*> que; 5 if (root != NULL) que.push(root); 6 int result = 0; 7 while (!que.empty()) { 8 int size = que.size(); 9 for (int i = 0; i < size; i++) { 10 TreeNode* node = que.front(); 11 que.pop(); 12 result++; // 记录节点数量 13 if (node->left) que.push(node->left); 14 if (node->right) que.push(node->right); 15 } 16 } 17 return result; 18 } 19 };标签:node,int,随想录,que,二叉树,深度,root,size From: https://www.cnblogs.com/zsqy/p/16773566.html