判断是不是完全二叉树
先有左节点再有右节点,递归判断
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <queue>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* @param root TreeNode类
* @return bool布尔型
*/
bool isCompleteTree(TreeNode* root) {
if(!root) return true;
queue<TreeNode*>q{
{root}};
bool end=false;
while(!q.empty()){
for(int i=0;i<q.size();i++){//一层一层判断
TreeNode* t=q.front(); q.pop();
if(!t) end=true;//为空,说明缺少左边
else{
if(end) return false;
q.push(t->left);//先进左节点
q.push(t->right);//再进右节点
}
}
}
return true;
}
};
判断是不是平衡二叉树
class Solution {
public:
int height(TreeNode* r){//计算树的高度
if(!r) return 0;
int rh=height(r->right);
int lh=height(r->left);
return max(lh, rh) + 1;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
if(!pRoot) return true;
int lh=height(pRoot->left);
int rh=height(pRoot->right);
if(abs(lh-rh)>1)return false;//绝对值>1
return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);//递归判断左右子树
}
};
二叉搜索树的最近公共祖先
int lowestCommonAncestor(TreeNode* root, int p, int q) {
int s=min(p, q), t=max(p, q);
//最小的比根大,说明答案在根的右边
if(s>root->val) return lowestCommonAncestor(root->right, p, q);
//同理,最大的比根小,说明答案在根的左边
if(t<root->val) return lowestCommonAncestor(root->left, p, q);
return root->val;
}
在二叉树中找到两个节点的最近公共祖先
需满足:
1. o1和o2分别位于这个节点的两个子树里,即如果存在一个节点,从左子树出发能找到o1或o2,从右子树出发也能找到,那就说明这个节点就是最近公共祖先节点
2. 注意特殊情况,因为有可能全部在左子树,或者右子树,那最近公共祖先点就是他们本身(离根更近的那个)
int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
if(!root) return 0;
if(root->val==o1 || root->val==o2) return root->val;
int l = lowestCommonAncestor(root->left, o1, o2);
int r = lowestCommonAncestor(root->right,o1, o2);
if(l && r) return root->val;
else if(l) return l;
else if(r) return r;
else return 0;
}