全球最实用的IT互联网信息网站!

AI人工智能P2P分享&下载搜索网页发布信息网站地图

当前位置:诺佳网 > 电子/半导体 > 区块链 >

LeetCode 236 最近公共祖先 Lowest Common Ancestor of a B

时间:2018-01-24 11:32

人气:

作者:admin

标签: leetcode  祖先  公共  236  最近 

导读:LeetCode 236 最近公共祖先 Lowest Common Ancestor of a Binary Tree-题目:找p和q的最近公共祖先 Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wik...

题目:找p和q的最近公共祖先
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).”

_______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4

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.
理解:

当遍历到一个root点的时候,

1.判断root是不是null如果root为null,那么就无所谓祖先节点,直接返回null就好了

2.如果root的左子树存在p,右子树存在q,那么root肯定就是最近祖先

3.如果pq都在root的左子树,那么就需要递归root的左子树,右子树同理

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(root == NULL || root == p || root ==q) return root; TreeNode* left = lowestCommonAncestor(root->left, p, q); TreeNode* right = lowestCommonAncestor(root->right, p, q); if(left && right){ return root; }else{ return left == NULL ? right : left; } }

温馨提示:以上内容整理于网络,仅供参考,如果对您有帮助,留下您的阅读感言吧!
相关阅读
本类排行
相关标签
本类推荐

CPU | 内存 | 硬盘 | 显卡 | 显示器 | 主板 | 电源 | 键鼠 | 网站地图

Copyright © 2025-2035 诺佳网 版权所有 备案号:赣ICP备2025066733号
本站资料均来源互联网收集整理,作品版权归作者所有,如果侵犯了您的版权,请跟我们联系。

关注微信