代码随想录_leetcode222 - leetcode110
leetcode222. 完全二叉树的结点个数
222. 完全二叉树的节点个数
给你一棵 完全二叉树 的根节点 root
,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h
层,则该层包含 1~ 2h
个节点。
示例 1:
输入:root = [1,2,3,4,5,6] 输出:6示例 2:
输入:root = [] 输出:0示例 3:
输入:root = [1] 输出:1
代码
// leetcode 222// 层序遍历迭代法
class Solution {
public:int countNodes(TreeNode* root) {if (root == nullptr){return 0;}queue<TreeNode*> treeQue;treeQue.push(root);TreeNode* cur;int count = 0;while (!treeQue.empty()){count++;cur = treeQue.front();treeQue.pop();if (cur->left != nullptr){treeQue.push(cur->left);}if (cur->right != nullptr){treeQue.push(cur->right);}}return count;}
};// 递归法 根节点 + 左子树结点 + 右子树结点
class Solution {
public:int countNodes(TreeNode* root) {if (root == nullptr){return 0;}return 1 + countNodes(root->left) + countNodes(root->right);}
};
leetcode 110.平衡二叉树
110. 平衡二叉树
难度简单1294收藏分享切换为英文接收动态反馈
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:true示例 2:
输入:root = [1,2,2,3,3,null,null,4,4] 输出:false示例 3:
输入:root = [] 输出:true
代码
//leetcode110 平衡二叉树
//递归
class Solution {
public://求高度int getHeight(TreeNode* cur){if (cur == nullptr){return 0;}return 1 + max(getHeight(cur->left), getHeight(cur->right));}bool isBalanced(TreeNode* root) {if (root == nullptr){return true;}if (abs(getHeight(root->left) - getHeight(root->right)) > 1){return false;}return isBalanced(root->left) && isBalanced(root->right);}
};//迭代法
class Solution {
public://求高度int getHeight(TreeNode* cur){if (cur == nullptr){return 0;}return 1 + max(getHeight(cur->left), getHeight(cur->right));}bool isBalanced(TreeNode* root) {if (root == nullptr){return true;}queue<TreeNode*> treeQue;TreeNode* cur;treeQue.push(root);while (!treeQue.empty()) {cur = treeQue.front(); treeQue.pop();if (abs(getHeight(cur->left) - getHeight(cur->right)) > 1) {return false;}if (cur->left) {treeQue.push(cur->left);}if (cur->right) {treeQue.push(cur->right);}}return true;}
};