智慧屏 安装 app如何提升家庭娱乐与教育体验的关键工具
1079
2022-08-23
[leetcode] 236. Lowest Common Ancestor of a Binary Tree
Description
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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1Output: 3Explanation: The LCA of nodes 5 and 1 is 3.
Example 2:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4Output: 5Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
Note:
All of the nodes’ values will be unique.p and q are different and both values will exist in the binary tree.
分析
题目的意思是:求二叉树中两个指定结点的最小公共祖先。
首先要先确定给的两个node是否都在tree里,如果都在tree里的话,就可以分成3种情况.第一种情况是两个节点是在公共祖先的左右两侧;第二种情况是都在树的左侧;第三种情况是都在树的右侧,如果是第二,第三种情况的话,公共祖先就在给定的两个点中比较上面的那一个。
代码一(c++)
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(!root||p==root||q==root){ return root; } TreeNode* left=lowestCommonAncestor(root->left,p,q); TreeNode* right=lowestCommonAncestor(root->right,p,q); if(left&&right){ return root; } return left ? left:right; }};
代码二 (python)
# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if(not root): return None if(root ==p or root==q): return root findLeft=self.lowestCommonAncestor(root.left,p,q) findRight=self.lowestCommonAncestor(root.right,p,q) if(not findLeft): return findRight if(not findRight): return findLeft return root
参考文献
[LeetCode] Lowest Common Ancestor of a Binary Tree 二叉树的最小共同父节点[LeetCode] Lowest Common Ancestor of a Binary Tree系列
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~