【LintCode】 88. 最近公共祖先

描述

給定一棵二叉樹,找到兩個節點的最近公共父節點(LCA)。

最近公共祖先是兩個節點的公共的祖先節點且具有最大深度。

假設給出的兩個節點都在樹中存在

樣例
樣例 1:

輸入:{1},1,1
輸出:1
解釋:
 二叉樹如下(只有一個節點):
         1
 LCA(1,1) = 1
樣例 2:

輸入:{4,3,7,#,#,5,6},3,5
輸出:4
解釋:
 二叉樹如下:

  4
 / \
3   7
   / \
  5   6

LCA(3, 5) = 4

解法

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
public:
    /**
     * @param root: The root of the binary search tree.
     * @param A and B: two nodes in a Binary.
     * @return: Return the least common ancestor(LCA) of the two nodes.
     */
    int Atop, Btop, top;
    TreeNode *a[100000], *b[100000], *ans[100000];
    bool find;
    void inorder(TreeNode *node, TreeNode *A, int flag) { 
        if (find==true)
            return;
        if (node == NULL)
            return;
        ans[++top] = node;
        if (A == node) {
            find = true;
            if (flag == 0) {
                Atop = top;
                for (int i = 1; i <= top; ++i)
                    a[i] = ans[i];
            } else {
                Btop = top;
                for (int i = 1; i <= top; ++i)
                    b[i] = ans[i];
            }
            return;
        }

        inorder(node->left, A, flag);
        if (find) return;
            
        inorder(node->right, A, flag);
        if (find) return;
          
        top --;
        
    }
    TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *A, TreeNode *B) {
        // write your code here
        top = 0; find = false;
        inorder(root, A, 0);

        top = 0; find = false;
        inorder(root, B, 1);
  
        Atop = min(Atop, Btop);
        Btop = Atop;

        while (a[Atop] != b[Btop]) {
            Atop --;
            Btop --;
        }
        return a[Atop];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章