Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to parse the nearest common ancestor of python binary tree

Shulou Source: shulou.com Published: 2022-06-01 14:13:57 10月02日 Update

This article introduces how to analyze the recent common ancestors of python binary tree, the content is very detailed, interested friends can refer to, I hope it can be helpful to you.

Given a binary tree, find the nearest common ancestor of the two specified nodes in the tree.

The recent common ancestor in Baidu encyclopedia is defined as: "for the two nodes p and Q with root tree T, the nearest common ancestor is expressed as a node x, satisfying that x is the ancestor of p and Q and that x is as deep as possible (a node can also be its own ancestor)."

For example, a binary tree is given as follows: root = [3pd5, 1, 6, 2, 0, 0, 8, null, and 7]

Example 1:

Input: root = [3, 5, 1, 6, 2, 0, 8, 7, 4], p = 5, Q = 1

Output: 3

Explanation: the nearest common ancestor of node 5 and node 1 is node 3.

Example 2:

Input: root = [3, 5, 1, 6, 2, 0, 8, 7, 4], p = 5, Q = 4

Output: 5

Explanation: the nearest common ancestor of node 5 and node 4 is node 5. Because by definition the nearest common ancestor node can be the node itself.

Description:

The values of all nodes are unique.

P and Q are different nodes and all exist in a given binary tree.

Solution 1:

1, if the two nodes are in the left and right subtree, return the current node

2, if it is all in the left subtree, the recursive left subtree

3, if it is all in the right subtree, recursive right subtree

Code implementation

/ * Definition for a binary tree node. * type TreeNode struct {* Val int * Left * TreeNode * Right * TreeNode * * / func lowestCommonAncestor (root * TreeNode, p * TreeNode, Q * TreeNode) * TreeNode {if rootworthy roomnil & & contain (root.Left,p) & & contain (root.Left,q) {return lowestCommonAncestor (root.Left,p,q)} if rootworthy roomnil & & contain (root.Right,p) & & contain (root.Right) Q) {return lowestCommonAncestor (root.Right,p,q)} return root} func contain (root * TreeNode, p * TreeNode) bool {if root==nil {return false} if root.Val==p.Val {return true} return contain (root.Left,p) | | contain (root.Right,p)}

Solution 2:

1, find the path from the root node to the two points

2. Remove the coincident part.

Code implementation

Func lowestCommonAncestor (root * TreeNode, p * TreeNode, Q * TreeNode) * TreeNode {var lrect r [] * TreeNode _, l=findPath (root,p) _, r=findPath (root,q) l=append ([] * TreeNode {root}, l...) R=append ([] * TreeNode {root}, r...) / / for iRO root

Tags: Nodes ancestors subtrees two code content more examples nodes solutions recursion help interpretation input output different good interests boys buddies Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Shulou Information Docker MariaDB MySQL