LeetCode 1123. 最深叶节点的最近公共祖先**(double)

具体思想:

。。。我真的是个傻逼。。。

自己想的是寻找出来最深节点,模仿之前的寻找两节点的祖先,逐个寻找出父亲节点;

类似于递归从底向上求深度,但是这次递归向上的深度是上层给的,头一次见到;

具体算法:

1. 寻找两节点父亲:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int getdepth(TreeNode* root){
        if(!root)
            return 0;
        return max(getdepth(root->left),getdepth((root->right)))+1;
    }

    void find(TreeNode* root,int depth,int maxdeep){
        if(!root)
            return;
        if(maxdeep==depth){
            st.push_back(root);
            return;
        }
        find(root->left,depth+1,maxdeep);
        find(root->right,depth+1,maxdeep);
    }

    bool postorder(TreeNode* root,TreeNode* &com_father,TreeNode* p,TreeNode* q){
        if(!root)
            return false;
        bool left=postorder(root->left, com_father,p,q);
        bool right=postorder(root->right, com_father,p,q);
        if((left&&right)||((left||right)&&(root==p||root==q)))
            com_father=root;
        if(left||right||root==p||root==q)
            return true;
        return false;
    }

    TreeNode* lcaDeepestLeaves(TreeNode* root) {
        int depth=getdepth(root);
        find(root,1,depth);
        while(st.size()!=1){
            TreeNode* com=nullptr;
            postorder(root, com, st[0], st[1]);
            st.erase(st.begin());
            st.erase(st.begin());
            st.push_back(com);
        }
        return st[0];
    }
private:
    vector<TreeNode*>st;
};

2.直接按照树的性质进行寻找:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int getdepth(TreeNode* root,int depth){
        if(!root)
            return depth;
        int left=getdepth(root->left,depth+1);
        int right=getdepth(root->right,depth+1);
        if(left==right&&pre<=left){
            res=root;
            pre=left;
        }
        return max(left,right);

    }

    TreeNode* lcaDeepestLeaves(TreeNode* root) {
        getdepth(root,1);
        return res;
    }
private:
    TreeNode* res=nullptr;
    int pre=0;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值