1 平衡二叉树
题目链接:leetcode110
平衡二叉树的条件是 左右子树长度差不超过1. 从上到下的递归方法需要不断去查询二叉树的左右子树的高度,然后再去做是否为平衡树的判断。
时间复杂度O(n^2)
自上向下的递归方法
class Solution {
public:
int getdepth(TreeNode* root){
if(root == NULL) return 0;
return max(getdepth(root->left),getdepth(root->right))+1;
}
bool isBalanced(TreeNode* root)
{
if(root == NULL) return true;
if(!root->left && !root->right) return true;
int leftdepth = getdepth(root->left);
int rightdepth = getdepth(root->right);
bool res = (abs(leftdepth-rightdepth) <=1);
return (isBalanced(root->left) && isBalanced(root->right) && res);
}
};
后序递归实现
逻辑思路:
- 如果一个节点它的子树不是平衡二叉树,那么它必然不是平衡二叉树。所以先遍历叶子节点,再遍历根节点。只能采取后序遍历的方法。
- 遍历三部曲之一:输入输出信息:每个子树的根节点信息,输出为子树的深度,但如果子树不为平衡树,那么也不需要直到它的深度了,直接返回-1即可。
- 遍历三部曲之二:判断终止条件。当节点为空时则返回0.
- 遍历三部曲之三:单步执行的步骤:判断左子树是否为平衡二叉树,判断右子树是否为平衡二叉树,判断根节点是否为平衡二叉树。如果不是,返回-1, 如果是返回该节点的高度。
class Solution {
public:
// 后序遍历
int getdepth(TreeNode* root){
if(root == NULL) return 0;
int leftheight = getdepth(root->left);
if(leftheight == -1) return -1; // 遍历左节点不为平衡二叉树
int rightheight = getdepth(root->right);
if(rightheight == -1 ) return -1; // 遍历右节点不为平衡二叉树
if(abs(leftheight-rightheight) >1) return -1; //判断该节点不是平衡二叉树
return max(leftheight,rightheight)+1; //如果都是的话,就返回当前节点的最大高度
}
bool isBalanced(TreeNode* root)
{
if(root == NULL) return true;
if(!root->left && !root->right) return true;
bool res = (getdepth(root) > 0);
return res;
}
};
2 二叉树的所有路径
题目链接:leetcode404
层序遍历
只要碰到没有左子树和右子树的情况就记录进去。多加一个queue用于记录所有的组合方式。
每个节点只有一个根节点。
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if(root==NULL) return res;
queue<TreeNode*> que;
queue<string> que_string;
que.push(root);
que_string.push(to_string(root->val));
while(!que.empty()){
auto tmpNode = que.front();
que.pop();
string path = que_string.front();
que_string.pop();
if(!tmpNode->left && !tmpNode->right) {
res.push_back(path);
}
else{
if(tmpNode->left){
que.push(tmpNode->left);
que_string.push(path+"->"+to_string(tmpNode->left->val));
}
if(tmpNode->right){
que.push(tmpNode->right);
que_string.push(path+"->"+to_string(tmpNode->right->val));
}
}
}
return res;
}
};
左叶子之和
题目链接:leetcode404
左叶子指的是,必须得是没有任何孩子的左侧节点。
class Solution {
public:
void sumLeftLeaves(TreeNode* root, int &sum){
if(root == NULL) return;
if(root->left) sumLeftLeaves(root->left, sum);
if(root->right) sumLeftLeaves(root->right, sum);
if(root->left && !root->left->left && !root->left->right) sum += root->left->val;
}
int sumOfLeftLeaves(TreeNode* root)
{
int sum=0;
sumLeftLeaves(root, sum);
return sum;
}
};