104.二叉树的最大深度
题目链接:力扣
class Solution { public: int result; void getdepth(TreeNode*node, int depth) { result = result > depth ? result : depth; if(node == NULL) return; if(node->left) { getdepth(node->left, depth+1); } if(node->right) { getdepth(node->right, depth+1); } } int maxDepth(TreeNode* root) { // 使用前序遍历实现,模拟求二叉树深度的过程 if(root == NULL) return 0; getdepth(root, 1); return result; } };
class Solution { public: int getheight(TreeNode* node) { if(node == NULL) return 0; int left = getheight(node->left); int right = getheight(node->right); int high = 1 + max(left, right); return high; } int maxDepth(TreeNode* root) { // 使用后序遍历来实现 return getheight(root); } };
111.二叉树的最小深度
题目链接:力扣
class Solution { public: int getdepth(TreeNode* node) { if(node == NULL) return 0; int left = getdepth(node->left); int right = getdepth(node->right); if(node->left == NULL && node->right) return 1+right; else if(node->left && node->right == NULL) return 1+left; else return 1+min(left,right); } int minDepth(TreeNode* root) { // 后序遍历 return getdepth(root); } };
class Solution { public: int minDepth(TreeNode* root) { // 迭代法(层序遍历) queue<TreeNode*> que; int depth = 0; if(root == NULL) return depth; que.push(root); while(!que.empty()) { int size = que.size(); depth++; for(int i = 0; i < size; i++) { TreeNode* tmp = que.front(); que.pop(); if(tmp->left) que.push(tmp->left); if(tmp->right) que.push(tmp->right); if(!tmp->left && !tmp->right) return depth; } } return depth; } };
222.完全二叉树的节点个数
题目链接:力扣
class Solution { public: int countNodes(TreeNode* root) { // 简单层序遍历统计节点 queue<TreeNode*> que; if(root == NULL) return 0; que.push(root); int result = 0; while(!que.empty()) { int size = que.size(); for(int i = 0; i < size; i++) { TreeNode* tmp = que.front(); que.pop(); result++; if(tmp->left) que.push(tmp->left); if(tmp->right) que.push(tmp->right); } } return result; } };
class Solution { public: int countNodes(TreeNode* root) { // 根据完全二叉树的特性来实现 // 结束条件 if(root == NULL) return 0; int leftCount = 0; int rightCount = 0; TreeNode* left = root->left; TreeNode* right = root->right; while(left) { left = left->left; leftCount++; } while(right) { right = right->right; rightCount++; } if(rightCount == leftCount) return (2 << leftCount) - 1; // 遍历过程 return countNodes(root->left) + countNodes(root->right) + 1; } };