题解 | #在二叉树中找到两个节点的最近公共祖先#

在二叉树中找到两个节点的最近公共祖先

https://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116

/**
 * struct TreeNode {
 *  int val;
 *  struct TreeNode *left;
 *  struct TreeNode *right;
 *  TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 
 在原来的基础上,添加对VisitCommonAncestor的返回值,以便找到目前节点之后,就可以不用再往下寻找了;
 */
class Solution {
 public:
  int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
    std::vector<TreeNode*> ancestors;
    std::vector<TreeNode*> o1_path, o2_path;
    VisitCommonAncestor(root, o1, ancestors, o1_path);
    ancestors.clear();
    VisitCommonAncestor(root, o2, ancestors, o2_path);

    auto i = 0;
    TreeNode* lca = nullptr;
    while (i < o1_path.size() && i < o2_path.size()) {
      if (o1_path[i] == o2_path[i])
        lca = o1_path[i];

      ++i;
    }

    return lca->val;
  }

  bool VisitCommonAncestor(TreeNode* root, int v,
                           std::vector<TreeNode*>& ancestors, std::vector<TreeNode*>& path) {
    if (root == nullptr)
      return false;

    ancestors.push_back(root);
    if (root->val == v) {
      path = ancestors;
      return true;
    }

    if (VisitCommonAncestor(root->left, v, ancestors, path) ||
        VisitCommonAncestor(root->right, v, ancestors, path) ) {
      return true;
    } else {
      ancestors.pop_back(); // 当它的左右子树都遍历完之后,就要走当前节点的上一层,所以,需要将当前节点从stack中移除;
      return false;
    }
  }
};

全部评论

相关推荐

本人一直追求WLB,对大小周深恶痛疾,刷到小红书说取消大小周大喜,看来跳槽的选择又多一个了
一枚大铁锤:至于冲不冲小红书,这是个问题,我先声明我不是这方面的专家,我觉得这件事还是要慎重评论,你问我为什么不给出回答,因为我一开始就说了,我不是这方面的专家
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务