算法竞赛备赛——【数据结构】二叉树

二叉树

二叉树的问题大多基于递归实现(面试较多 力扣的二叉树的题会多一些 竞赛遇到的较少)

n个节点 x个度为0的节点 有x-1个度为2的节点

(线的总数 2n2+n1=n2+n1+n0-1)n0=n2+1

有一个先序序列1 2 3 4,有___棵树二叉树满足这个先序序列:

卡特兰数: C 2 n n / ( n + 1 ) C^{n}_{2n}/(n+1) C2nn/(n+1)

先序+中序可以确定一棵树

先序对应入栈 中序对应出栈顺序 用卡特兰数可求

LCR 145. 判断对称二叉树 - 力扣(LeetCode)

class Solution {
public:
    bool check(TreeNode* l,TreeNode* r){
        if(l==NULL&&r==NULL) return true;
        if(l==NULL||r==NULL) return false;
        if(l->val==r->val){
            return check(l->right,r->left)&&check(l->left,r->right);
        }
        return false;
    }
    bool checkSymmetricTree(TreeNode* root) {
        if(root==NULL) return true;
        else return check(root->left,root->right);
    }
};

236. 二叉树的最近公共祖先 - 力扣(LeetCode)

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==NULL) return NULL;
        if(p==root||q==root) return root;

        TreeNode* l=lowestCommonAncestor(root->left,p,q);
        TreeNode* r=lowestCommonAncestor(root->right,p,q);

        if(l==NULL) return r;
        if(r==NULL) return l;
        if(l&&r) return root;
        return NULL;    
    }
};

你可能感兴趣的:(算法竞赛备赛,算法,数据结构,c++,蓝桥杯)