zoukankan      html  css  js  c++  java
  • LeetCode "Lowest Common Ancestor of a BST"

    First please note, it is BST. So it is about value compare.

    class Solution 
    {
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 
        {
            if(!root) return nullptr;
            int sm = std::min(p->val, q->val);
            int lg = std::max(p->val, q->val);
            
            if( (root->val > sm && root->val < lg) || (root->val == sm || root->val == lg))
                return root;
            else if(root->val > lg)    
                return lowestCommonAncestor(root->left, p, q);
            else if(root->val < sm)
                return lowestCommonAncestor(root->right, p, q);
            return nullptr;
        }
    };

    And what if it is a general tree, not necessarily a BST?

    // unsigend char as record
    typedef unsigned char uchar;
    class Solution 
    {
        TreeNode *pret;
        uchar go(TreeNode *root, TreeNode* p, TreeNode *q)
        {
            if (!root) return 0;
            uchar rec = 0;
    
            rec |= (root == p) ? 0x1 : 0;
            rec |= (root == q) ? 0x2 : 0;
    
            uchar rleft = go(root->left, p, q);
            if(rleft ==0x3)
            {
                return 0x3;
            }
            if (rec && ((rec | rleft) == 0x3))
            {
                pret = root;
                return 0x3;
            }
    
            uchar rright= go(root->right, p, q);
            if(rright ==0x3) return 0x3;
            if (rec && ((rec | rright) == 0x3))
            {
                pret = root;
                return 0x3;
            }
    
            if ((rleft | rright )== 0x3)
            {
                pret = root;
            }
    
            return rec | rleft | rright;
        }
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 
        {
            pret = nullptr;
            go(root, p, q);
            return pret;
        }
    };
  • 相关阅读:
    个人作业——软件评测
    软件工程实践2019第五次作业
    18年今日头条笔试第一题题解:球迷(fans)
    游戏2.1版本
    游戏2.0版本 代码
    游戏2.0版本
    改进版游戏代码
    改进版游戏
    2017.1.13之审判日
    找朋友 的内存超限代码
  • 原文地址:https://www.cnblogs.com/tonix/p/4637974.html
Copyright © 2011-2022 走看看