236. Lowest Common Ancestor of a Binary Tree

/*
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between 
two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a 
node to be a descendant of itself).”

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4
For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of 
nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
思路11:利用二個棧來存儲兩個節點的路徑
2:使路徑長的節點,從棧頂pop節點,直到兩個棧的長度相同
3:開始從棧頂比較,如果相等,即爲最低的父節點

思路2:
    兩個節點在同一個子樹或不同子樹,在同一個子樹直接返回遇到的第一個節點即可;
    在不同的子樹,當兩個節點都遇到後,下一個父節點即是所求
*/



/**
 * 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) return NULL;
        stack<TreeNode*> sp,sq;
        findNodePath(root,q,sq);
        findNodePath(root,p,sp);
        while(!sq.empty() && !sp.empty()){
            if(sq.size()>sp.size())
                sq.pop();
            else if(sq.size()<sp.size())
                sp.pop();
            else
                break;
        }
         while(!sq.empty() && !sp.empty()){
            if(sq.top()==sp.top())
                return sq.top();
            sq.pop();
            sp.pop();
         }
         return NULL;
    }
    void findNodePath(TreeNode* root,TreeNode* target,stack<TreeNode*> &st){
        if(!root) return;
        st.push(root);
        if(st.top()==target) return;
        if(root->left) findNodePath(root->left,target,st);  
        if(st.top()!=target && root->right) findNodePath(root->right,target,st);
        if(st.top()!=target) st.pop();
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root || root==p || root==q) return root;
        TreeNode* left=lowestCommonAncestor(root->left,p,q);
        TreeNode* right=lowestCommonAncestor(root->right,p,q);
        return !left ? right : !right ? left : root;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章