zoukankan      html  css  js  c++  java
  • 面试题6:二叉树最近公共节点(LCA)《leetcode236》

    Lowest Common Ancestor of a Binary Tree(二叉树的最近公共父亲节点)

    Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

    According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” 
    这里写图片描述 
    For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

    给定一个二叉树和所要查找的两个节点,找到两个节点的最近公共父亲节点(LCA)。比如,节点5和1的LCA是3,节点5和4的LCA是5。

     1 class Solution {
     2 public:
     3     TreeNode* lowestCommonAncestor(TreeNode* root,TreeNode* p,TreeNode* q){
     4         if(root == nullptr || root == p || root == q){
     5             return root;
     6         }
     7         TreeNode* left = lowestCommonAncestor(root->left,p,q);
     8         TreeNode* right = lowestCommonAncestor(root->right,p,q);
     9         if(left && right) return root;
    10         if(left == nullptr) return right;
    11         if(right == nullptr) return left;
    12     }
    13 };
  • 相关阅读:
    Peer code review
    分析图书管理系统的5W1H
    项目风险分析作业
    课堂练习
    功能分析四个象限
    Android需求分析作业
    电梯演说模板练习
    敏捷流程的理解
    团队模型的小组辩论
    结对编程任意Demo
  • 原文地址:https://www.cnblogs.com/wxquare/p/6848528.html
Copyright © 2011-2022 走看看