68 -. II Binary Tree recent common ancestor

Title: Given a binary tree, find the nearest common ancestor of the two specified nodes of the tree. https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/submissions/

 EDITORIAL: This question is different from the 68-I binary search tree common ancestor https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-zui-jin-gong- -Xian-zu-Gong lcof / (binary search tree having a left node <parent node <right node properties), that question and solutions code as follows:

# Solving ideas if you want to find any two nodes is equal to a 1. The value of the root node, or two nodes that are located on both sides of the root node refers to the value of the head node returns. 2. If the two values of the root node in the left and look only at the left subtree, 3. Otherwise look in the right subtree. 
# Note that returns the value of the node other than the node 
class Solution:
     DEF lowestCommonAncestor (Self, the root: ' the TreeNode ' , P: ' the TreeNode ' , Q: ' the TreeNode ' ) -> ' the TreeNode ' :
         IF p.val> Q. val:
            p,q = q,p
        if p==root or q == root:
            return root
        if p.val<root.val and q.val> root.val:
            return root
        if p.val<root.val and q.val<root.val:
            return self.lowestCommonAncestor(root.left,p,q)
        if p.val>root.val and q.val>root.val:
            return self.lowestCommonAncestor(root.right,p,q)

For this question:

Method One saving path in the way of thinking:

The first: to our hypothesis tree node contains a pointer pointing to a parent node

If the parent node with the pointer reaches the reverse path 4 is able to get out 4-> 2-> 5-> 3 and arriving reverse path 6 is 6-> 5-> 3 since the node has a parent pointer, so the the first problem is the conversion issue has become a common node request of two lists;

The second: the use of an array of storage path

We can use the two storage arrays paths, with preorder storage forward path, such as the node 4 is the forward path 3-> 5-> 2-> 4, node 6 is the forward path 3-> 5-> 6, from the beginning to find the first node before the node is not identical to, the example refers to node 5;

The second idea is the code:

# 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
        """
        stack_1 = []
        stack_2 = []
        def dfs(root, node, stack):
            if not root:
                return False
            stack.append(root)
            if root.val == node.val:
                return True          
            if (dfs(root.left, node, stack) or dfs(root.right, node, stack)):
                return True
            stack.pop()
            
        dfs(root, p, stack_1)
        dfs(root, q, stack_2)
        i = 0
        while i < len(stack_1) and i<len(stack_2) and stack_1[i] == stack_2[i]:
            result = stack_1[i]
            i += 1
        return result

 

Method 2 recursive

[Thinking]

Because lowestCommonAncestor (root, p, q) function is to find the common ancestor to root for the two root nodes p and q, so recursive body discussed three cases:

1. If p and q are the root of the left and right node, then the root is the most recent common ancestor we are looking for;

P and q are 2. If the root node left, then return lowestCommonAncestor (root.left, p, q);

3. If p and q are right root node, return lowestCommonAncestor (root.right, p, q);

Boundary conditions are discussed:

1. If the root is null, it means we've found the bottom, and did not return null to find;

And p is equal to 2. If the root or equal to q, root is returned;

3. If the left sub-tree is not found, the recursive function returns null, proved p and q are the same on the right side of the root, then the node is the final common ancestor found the right subtree;

4. If you did not find the right sub-tree, the recursive function returns null, proved p and q are the same in the left side of the root, then the node is the final common ancestor left subtree found;

# 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 not root or root == p or root == q:
            return root
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)

        if not left:
            return right
        if not right:
            return left
        return root

 

 

 

 

Guess you like

Origin www.cnblogs.com/USTC-ZCC/p/12547620.html