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

区块链

579人已加入

描述

题目:找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; } }

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 相关推荐

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分