[C++] LeetCode 236. The nearest common ancestor of a binary tree

topic

Given a binary tree, find the nearest common ancestor of two specified nodes in the tree.
The definition of the nearest common ancestor in Baidu Encyclopedia: "For Ttwo nodes u, v, of a rooted tree, the nearest common ancestor represents a node xthat satisfies xyes u, vand the depth of the ancestor xis as large as possible." (A node can also be itself Ancestor of )
write picture description here
For example, node 5and node 1's nearest common ancestor is node 3; node 5and node 4's nearest common ancestor is node 5, because by definition, a node can be its own ancestor.

answer

This question should be a common interview question. You can consider directly using two arrays to record the paths of uand respectively v, and then traverse the two paths to find the common ancestor

code

/**
 * 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:
    bool getAncestor(TreeNode* root,TreeNode *p,vector<TreeNode*> &vec){
        if(root==NULL) return false;
        if(root==p){
            vec.push_back(root);
            return true;
        }
        if(getAncestor(root->left,p,vec)||getAncestor(root->right,p,vec)){
            vec.push_back(root);
            return true;
        }
        return false;

    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        vector<TreeNode*> vp,vq;
        getAncestor(root,p,vp);
        getAncestor(root,q,vq);
        int n=vp.size(),m=vq.size();
        while(n>0&&m>0&&vp[n-1]==vq[m-1]){
            n--;
            m--;
        }
        return vp[n];
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324800121&siteId=291194637