『递归的妙用』题解 | #在二叉树中找到两个节点的最近公共祖先#

在二叉树中找到两个节点的最近公共祖先

http://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116

需要多做几遍的题目。。

  • 『刚开始做的时候卡了。。。』
  • 递归的妙用
/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 * };
 */



class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @param o1 int整型 
     * @param o2 int整型 
     * @return int整型
     */
    int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
        // write code here

        if( nullptr==root ) return 0x3f3f3f;//表示没有公共祖先
        if( o1==root->val || o2==root->val )
        {
            return root->val;//当前节点就是最近公共祖先
        }
        //去左子树找最近公共祖先
        int Left=lowestCommonAncestor( root->left , o1,  o2);
        //去右边子树找最近公共祖先
        int Right=lowestCommonAncestor( root->right , o1, o2);

        if( 0x3f3f3f==Right ) return Left;
        if( 0x3f3f3f==Left ) return Right;
        return root->val;

    }
};
全部评论

相关推荐

不知道怎么取名字_:两个方向 1.简历针对性准备下 2.面试前也需要准备的 主要还是要看各个公司需求,看公司行业和岗位描述,那里面已经写了对技术的需求,一份简历,不可能和所有嵌入式岗位都匹配的
投递北京经纬恒润科技股份有限公司等公司6个岗位
点赞 评论 收藏
分享
jay118_:实在担心的话,就把你账号里面的认证人脸改成你室友的脸,让他每天帮你刷。要是人脸写死了就每天打视频电话刷脸。办法总比困难多。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务