236. Lowest Common Ancestor of a Binary Tree
Posted Premiumlab
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了236. Lowest Common Ancestor of a Binary Tree相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/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 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.
Sol:
Bottom-up.
Find where is p or q.
1) if p or q is the root, return root
2) if p and q are on both sides of the tree, return root
3) if p and q are on left subtree, return left node.
4) if p and q are on right subtree, return right node.
To make the logic of 3) and 4) more apprent to computers, we use left/right variables to check if p and q exist on left/right subtree. # simple discrete mathematics
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ # if root is null or find p or q if root == None or root == q or root == p: return root # find p or q in the left subtree left = self.lowestCommonAncestor(root.left, p, q) # find p or q in the right subtree right = self.lowestCommonAncestor(root.right, p, q) if left and right: return root else: if not left: return right else: return left
Similar Problem:
235. Lowest Common Ancestor of a Binary Search Tree
In the BSTproblem, we use the one BST attribute, values of p and q, to check which side p and q are on. We can also use iteration on it.
以上是关于236. Lowest Common Ancestor of a Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 236. Lowest Common Ancestor of a Binary Tree
236. Lowest Common Ancestor of a Binary Tree
236. Lowest Common Ancestor of a Binary Tree
236. Lowest Common Ancestor of a Binary Tree