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 };
  • 相关阅读:
    C# 中的栈和堆
    C# 中的基本数值类型
    多个 .NET 框架
    简单介绍托管执行和 CLI
    C# 控制台输入和输出
    在 C# 中使用变量
    C# 语法基础
    LeetCode 1482. 制作 m 束花所需的最少天数
    C# 基础(更新中)
    圆形靶内的最大飞镖数量
  • 原文地址:https://www.cnblogs.com/wxquare/p/6848528.html
Copyright © 2011-2022 走看看