110. 平衡二叉树
方法:递归
利用后序来求高度,标记-1为不平衡情况
class Solution {
public:
int getheight(TreeNode* root) {
if (root == nullptr) return 0;
int leftheight = getheight(root->left);
if (leftheight == -1) return -1;
int rightheight = getheight(root->right);
if (rightheight == -1) return -1;
if (abs(leftheight - rightheight) > 1) return -1;
return 1 + max(leftheight, rightheight);
}
bool isBalanced(TreeNode* root) {
if (getheight(root) == -1) return false;
return true;
}
};
257. 二叉树的所有路径
方法:递归
前序遍历
class Solution {
public:
vector<string> ret;
vector<string> binaryTreePaths(TreeNode* root) {
string path = "";
if (root == nullptr) return ret;
dfs(root, path);
return ret;
}
void dfs(TreeNode* root, string path)//注意不能是&不然就会导致回溯失败
{
path += to_string(root->val);
if (root->left == nullptr && root->right == nullptr)
{
ret.push_back(path);
return;
}
path += "->";
if(root->left) dfs(root->left, path);
if (root->right) dfs(root->right, path);
}
};
404. 左叶子之和
该题关键在于是左叶子而不是左结点,如果该节点的左节点不为空,该节点的左节点的左节点为空,该节点的左节点的右节点为空,则找到了一个左叶子
方法:递归
1.后序遍历
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr) return 0;
if (root->left == nullptr && root->right == nullptr) return 0;
int leftsum = sumOfLeftLeaves(root->left);
if (root->left && !root->left->left && !root->left->right) leftsum = root->left->val;
int rightsum = sumOfLeftLeaves(root->right);
return leftsum + rightsum;
}
};
该方法必须找到父结点才能判断子结点,下面提供一种可以通过前序遍历就判断出结点是否是左叶子的方法:利用flag标志
2.前序遍历
class Solution {
private:
int sum = 0;
public:
void dfs(TreeNode* root, int flag) {
if (root == nullptr) return;
if (!root->left && !root->right && flag == 1) sum += root->val;
dfs(root->left, 1);
dfs(root->right, 0);
}
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr) return 0;
dfs(root, 0);
return sum;
}
};
222. 完全二叉树的节点个数
方法:递归
如果是普通二叉树则前中后序以及层序都可以写成简单的代码解答,但得遍历完树,这里只展示没有遍历完树的时间复杂度更低的算法:
利用完全二叉树里的满二叉树可以利用数学公式快速计算的方法
class Solution {
public:
int countNodes(TreeNode* root) {
if (root == nullptr) return 0;//递归终止条件1
int leftdepth = 0, rightdepth = 0;
TreeNode *left = root->left, *right = root->right;
while (left) {
left = left->left;
leftdepth++;
}
while (right) {
right = right->right;
rightdepth++;
}
if (leftdepth == rightdepth) return (2 << leftdepth) - 1;//递归终止条件2
int leftnodes = countNodes(root->left);//左
int rightnodes = countNodes(root->right);//右
return leftnodes + rightnodes + 1;//中//后序
}
};