class Solution {
private:
unordered_map<int, int> index;
public:
TreeNode* myBuildTree(vector<int>& preorder, vector<int>& inorder, int preorder_left, int preorder_right, int inorder_left, int inorder_right) {
if (preorder_left > preorder_right) {
return nullptr;
}
// 前序遍历中的第一个节点就是根节点
int preorder_root = preorder_left;
// 在中序遍历中定位根节点
int inorder_root = index[preorder[preorder_root]];
// 先把根节点建立出来
TreeNode* root = new TreeNode(preorder[preorder_root]);
// 得到左子树中的节点数目
int size_left_subtree = inorder_root - inorder_left;
// 递归地构造左子树,并连接到根节点
// 先序遍历中「从 左边界+1 开始的 size_left_subtree」个元素就对应了中序遍历中「从 左边界 开始到 根节点定位-1」的元素
root->left = myBuildTree(preorder, inorder, preorder_left + 1, preorder_left + size_left_subtree, inorder_left, inorder_root - 1);
// 递归地构造右子树,并连接到根节点
// 先序遍历中「从 左边界+1+左子树节点数目 开始到 右边界」的元素就对应了中序遍历中「从 根节点定位+1 到 右边界」的元素
root->right = myBuildTree(preorder, inorder, preorder_left + size_left_subtree + 1, preorder_right, inorder_root + 1, inorder_right);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n=preorder.size();
for(int i=0;i<n;i++){
index[inorder[i]]=i;
}
return myBuildTree(preorder,inorder, 0, n - 1, 0, n - 1);
}
知识点补充:
二叉搜索树(Binary Search Tree):也叫做二叉查找树、有序二叉树或者排序二叉树。是指一棵空树或者具有下列性质的二叉树:
- 如果任意节点的左子树不为空,则左子树上所有节点的值均小于它的根节点的值。
- 如果任意节点的右子树不为空,则右子树上所有节点的值均大于它的根节点的值。
- 任意节点的左子树、右子树均为二叉搜索树。
归为一句话(左<根<右)
如果我们以中序遍历的方式遍历整个二叉搜索树时,会得到一个严格递增序列.
那么很明显这道题,我们只需要中序遍历一下就可啦
class Solution {
public:
vector<int> res;
void inorder(TreeNode* root){
if(!root) return ;
if(root->left) inorder(root->left);
res.push_back(root->val);
if(root->right)inorder(root->right);
}
bool isValidBST(TreeNode* root) {
if(!root) return true;
inorder(root);
int n= res.size();
for(int i=0;i<n-1;i++){
if(res[i]>=res[i+1]) return false;
}
return true;
}
};
110. 平衡二叉树(AVL树)
知识点:
平衡二叉搜索树(Balanced Binary Tree):一种结构平衡的二叉搜索树。即叶节点高度差的绝对值不超过 1,并且左右两个子树都是一棵平衡二叉搜索树。平衡二叉树可以在 内完成插入、查找和删除操作。最早被发明的平衡二叉搜索树为 「AVL 树(Adelson-Velsky and Landis Tree))」。
AVL 树满足以下性质:
- 空二叉树是一棵 AVL 树。
- 如果 T 是一棵 AVL 树,那么其左右子树也是 AVL 树,并且 |ℎ(left)−ℎ(right)|≤1,ℎ(left)是左子树的高度,ℎ(right) 是右子树的高度。
- AVL 树的高度为。
根据定义来就可以
class Solution {
public:
int hight(TreeNode* root){
if(!root) return 0;
return max(hight(root->left),hight(root->right))+1;
}
bool isBalanced(TreeNode* root) {
if(!root) return true;
if(abs(hight(root->left)-hight(root->right))>1) return false;
return isBalanced(root->left)&&isBalanced(root->right);
}
};
补充一下平衡因子:
节点的「平衡因子 balance factor」定义为节点左子树的高度减去右子树的高度,同时规定空节点的平衡因子为 0 。
/* 获取平衡因子 */
int balanceFactor(TreeNode *node) {
// 空节点平衡因子为 0
if (node == nullptr)
return 0;
// 节点平衡因子 = 左子树高度 - 右子树高度
return height(node->left) - height(node->right);
}