• LeetCode 236. 二叉树的最近公共祖先


    题目链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/

    给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

    百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

     

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     struct TreeNode *left;
     6  *     struct TreeNode *right;
     7  * };
     8  */
     9 struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
    10         if(root==p||root==q||!root)return root;
    11         struct TreeNode* left=lowestCommonAncestor(root->left, p, q);
    12         struct TreeNode* right=lowestCommonAncestor(root->right, p, q);
    13         if(!left&&!right) return NULL;
    14         else if(left&&!right) return left;
    15         else if(right&&!left) return right; 
    16         return root;
    17 }
  • 相关阅读:
    hashlib模块
    logging模块
    Python的富比较方法
    格式化符号说明
    __str__与__repr__区别
    2014-07-18 10:25

    2014-07-17 17:04
    2014-07-17 16:44
    2014-07-16 15:54
  • 原文地址:https://www.cnblogs.com/shixinzei/p/11871320.html
Copyright © 2020-2023  润新知