(C++)LeetCode#236. Lowest Common Ancestor of a Binary Tree

  • 题目:给定一个棵二叉树的两个节点o1/o2,求两个节点的最近公共祖先(LCA)
  • 难度:Medium
  • 思路:
    • 方法1.记录路径:先遍历二叉树,分别得到从根节点到o1/o2的两个路径存储在vector中,遍历两个vector得到最近的相等的节点
    • 方法2.不记录路径:通过先序遍历二叉树,先判断当前遍历的节点是否为o1/o2,如果是则直接返回当前节点,否则继续遍历左子树、右子树,如果左子树返回结果和右子树返回结果同时存在,说明当前节点为最近公共祖先;否则判断左子树返回结果是否为空,如果不为空则返回左子树遍历结果,为空就返回右子树遍历结果
  • 代码:
方法一
class Solution {
public:
    bool getAncestor(TreeNode* root, TreeNode* node, vector &vec) {
        if (root == NULL) {
            return false;
        }
        if (root == node) {
            vec.push_back(root);
            return true;
        }
        if (getAncestor(root->left, node, vec) || getAncestor(root->right, node, vec)) {
            vec.push_back(root);
            return true;
        }
        return false;
    }

public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        vector lvec, rvec;//vector第一个节点是p或者q
        getAncestor(root, p, lvec);
        getAncestor(root, q, rvec);
        TreeNode* ancestor;
        int m = lvec.size();
        int n = rvec.size();
        while(m >0 && n > 0 && lvec[m-1]==rvec[n-1]){
            m--;
            n--;
        }
        return lvec[m];
    }
};
方法二
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root == NULL || root == p || root == q) {
            return root;
        }
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        if (left && right) {
            return root;
        }
        return left?left:right;
    }
};

你可能感兴趣的:((C++)LeetCode#236. Lowest Common Ancestor of a Binary Tree)