题解 | #二叉搜索树的最近公共祖先#

二叉搜索树的最近公共祖先

http://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f

越写越不会

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
  public:
    int lowestCommonAncestor(TreeNode* root, int p, int q) {
      int res;
      std::vector<int> p_path, q_path;
      
      find_path(p_path, root, p);
      find_path(q_path, root, q);
      
      for (int i = 0; i < p_path.size() && i < q_path.size(); ++i) {
        if (p_path[i] == q_path[i]) {
          res = p_path[i];
        }
      }
      
      return res;
    }
  private:
    void find_path(std::vector<int> &path, TreeNode *root, int target) {
      while (root->val != target) {
        path.push_back(root->val);
        if (root->val > target) {
          root = root->left;
        } else {
          root = root->right;
        }
      }
      //  结点本身也在路径的一部分
      path.push_back(root->val);
    }
};
全部评论

相关推荐

05-21 15:47
门头沟学院 Java
浪漫主义的虹夏:项目有亮点吗,第一个不是纯玩具项目吗,项目亮点里类似ThreadLocal,Redis储存说难听点是花几十分钟绝大部分人都能学会,第二个轮子项目也没体现出设计和技术,想实习先沉淀,好高骛远的自嗨只会害了自己
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务