1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

236.Lowest Common Ancestor of a Binary Tree

Posted at

問題内容

入力される2つの数字に共通する祖先のうち最も近い層にある祖先を探すプログラムを書く

sample
class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if not root or root == p or root == q:
            return root
        
        l = self.lowestCommonAncestor(root.left, p, q)
        r = self.lowestCommonAncestor(root.right, p, q)

        if l and r:
            return root
        return l or r

ポイント

  • 再帰的に呼び出すことで目的のノードが出力されるようにする
  • 各点の呼び出しで最初にrootがNone、p、qのいずれに当てはまるかをチェックする
  • 左右のサブツリーに目的ノードがあるか調べるために再帰呼び出し
  • lとrの両方から値が帰ってくれば、その親ノードが目的ノード
  • 片方から値が返され、もう片方がNoneなら返された値が目的ノードである
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?