码迷,mamicode.com
首页 > 其他好文 > 详细

Lowest Common Ancestor of a Binary Tree

时间:2015-07-15 22:53:52      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

题目地址:点击打开链接

解法一:对于深度过高的case过不了。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==NULL)return NULL;
        p1=p;
        p2=q;
        dfs(root,1);
        while(num1!=num2){
            if(num1>num2)num1=num1>>1;
            else num2=num2>>1;
        }
        ansNum=num1;
        getNode(root,1);
        return ansNode;
    }
private:
    int num1,num2,ansNum;
    TreeNode *p1,*p2,*ansNode;
    void dfs(TreeNode *root,int num){
        if(root){
            if(root==p1)num1=num;
            if(root==p2)num2=num;
            dfs(root->left,2*num);
            dfs(root->right,2*num+1);
        }
    }
    void getNode(TreeNode *root,int num){
        if(root){
            if(num==ansNum)ansNode=root;
            getNode(root->left,2*num);
            getNode(root->right,2*num+1);
        }
    }
};

解法二:全部能过。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        ans=NULL;
        dfs(root,p,q);
        return ans;
    }
private:
    TreeNode *ans;
    TreeNode* dfs(TreeNode *root,TreeNode *p,TreeNode *q){
        if(root&&ans==NULL){
            TreeNode* p1=dfs(root->left,p,q);
            TreeNode* p2=dfs(root->right,p,q);
            bool x=false,y=false;
            if(root==p||p1==p||p2==p)x=true;
            if(root==q||p1==q||p2==q)y=true;
            if(x&&y){
                ans=root;
                return NULL;
            }
            if(x)return p;
            if(y)return q;
            return NULL;
        }
        return NULL;
    }
};



版权声明:本文为博主原创文章,未经博主允许不得转载。

Lowest Common Ancestor of a Binary Tree

标签:

原文地址:http://blog.csdn.net/leizh007_ios/article/details/46898283

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!