236. Lowest Common Ancestor of a Binary Tree

来源:互联网 发布:万国数据招聘 编辑:程序博客网 时间:2024/05/16 14:56

考察点:DFS;
思路:首先根据一个搜索出到两个指针所指对象的path,存放在vector中,然后反转该vector,前面的元素是从根节点出发的节点路径,找出第一个不同的元素,返回之前的元素就可;
C++ 代码:

/** * 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 root;        vector<TreeNode*> p_path, q_path;        if (DFS(root, p, p_path)) {            reverse(p_path.begin(), p_path.end());        }        if (DFS(root, q, q_path)) {            reverse(q_path.begin(), q_path.end());        }        int i=0;        while(p_path[i] == q_path[i] && i<p_path.size() && i<q_path.size()) i++;        return p_path[i-1];    }    bool DFS(TreeNode* node, TreeNode* target, vector<TreeNode*> & path) {        if (node == target) {            path.push_back(node);            return true;        }        if (node == NULL) {            return false;        }        if (DFS(node->left, target, path) || DFS(node->right, target, path)) {            path.push_back(node);            return true;        }        return false;    }};

另外discuss里面的大神写法:

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;}