day16--binary tree

 Judging whether it is a complete binary tree

 First there is a left node and then a right node, recursive judgment

/**
 * 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;
    }
};

Judging whether it is a balanced binary tree

 

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);//递归判断左右子树
    }
};

The nearest common ancestor of a binary search tree

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;
    }

Find the nearest common ancestor of two nodes in a binary tree

Need to meet:

1. o1 and o2 are respectively located in the two subtrees of this node, that is, if there is a node, o1 or o2 can be found from the left subtree, and can also be found from the right subtree, it means that this node is the nearest common ancestor Node
2. Pay attention to special cases, because it is possible that they are all in the left subtree or the right subtree, and the nearest common ancestor point is themselves (the one closer to the root)

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;
    }

Guess you like

Origin blog.csdn.net/qq_54809548/article/details/131119507