二叉樹的堂兄弟節點
在二叉樹中,根節點位於深度 0 處,每個深度為 k 的節點的子節點位於深度 k+1 處。
如果二叉樹的兩個節點深度相同,但父節點不同,則它們是一對堂兄弟節點。
我們給出了具有唯一值的二叉樹的根節點 root,以及樹中兩個不同節點的值 x 和 y。
只有與值 x 和 y 對應的節點是堂兄弟節點時,才返回 true。否則,返回 false。
輸入:root = [1,2,3,null,4,null,5], x = 5, y = 4
輸出:true
class Solution(object):
def isCousins(self, root, x, y):
parent = {}
depth = {}
def dfs(node, par = None):
if node:
depth[node.val] = 1 + depth[par.val] if par else 0
parent[node.val] = par
dfs(node.left, node)
dfs(node.right, node)
dfs(root)
return depth[x] == depth[y] and parent[x] != parent[y]
View Code
link:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof
describe:
給定一個二叉搜索樹【值是有規律的】, 找到該樹中兩個指定節點的最近公共祖先。
百度百科中最近公共祖先的定義為:“對於有根樹 T 的兩個結點 p、q,最近公共祖先表示為一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度盡可能大(一個節點也可以是它自己的祖先)。”
例如,給定如下二叉搜索樹: root = [6,2,8,0,4,7,9,null,null,3,5]
示例 1:
輸入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
輸出: 6
解釋: 節點 2 和節點 8 的最近公共祖先是 6。
示例 2:
輸入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
輸出: 2
解釋: 節點 2 和節點 4 的最近公共祖先是 2, 因為根據定義最近公共祖先節點可以為節點本身。
說明:
所有節點的值都是唯一的。
p、q 為不同節點且均存在於給定的二叉搜索樹中。
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return
if root.val > p.val and root.val >q.val:
return self.lowestCommonAncestor(root.left,p,q)
if root.val < p.val and root.val < q.val:
return self.lowestCommonAncestor(root.right,p,q)
return root
方式二:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if p.val > q.val:p,q=q,p
while root:
if p.val > root.val and q.val>root.val:
root = root.right
elif p.val < root.val and q.val < root.val:
root = root.left
else:
break
return root
View Code
link:https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof
describe:
給定一個二叉樹【值是無規律的】, 找到該樹中兩個指定節點的最近公共祖先。
百度百科中最近公共祖先的定義為:“對於有根樹 T 的兩個結點 p、q,最近公共祖先表示為一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度盡可能大(一個節點也可以是它自己的祖先)。”
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if not root or root.val == p.val or root.val == q.val: return root
l = self.lowestCommonAncestor(root.left, p , q)
r = self.lowestCommonAncestor(root.right, p , q)
return root if l and r else l or r