【leetcode】236. Lowest Common Ancestor of a Binary Tree

题目如下:

解题思路:【leetcode】235. Lowest Common Ancestor of a Binary Search Tree类似,但是本题不是BST树。我的解题思路是把从根节点到p和q的路径找出来,以题目的example 2为例,p的路径是"L" (L表示左,R表示右),q的路径"LRR"。比较两个路径,得到想同的最长前缀,这个前缀对应的节点就是结果。

代码如下:

# 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):
    p_path, q_path = '', ''
    def helper(self,node, p, q, path):
        if node.val == p.val:
            self.p_path = path
        if node.val == q.val:
            self.q_path = path
        if node.left != None:
            self.helper(node.left, p, q, path + 'L')
        if node.right != None:
            self.helper(node.right, p, q, path + 'R')
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if root == None:
            return root
        self.p_path = ''
        self.q_path = ''
        self.helper(root,p,q,'')
        path = ''
        for i in range(min(len(self.p_path),len(self.q_path))):
            if self.p_path[i] != self.q_path[i]:
                break
            path += self.p_path[i]

        node = root
        while len(path) > 0:
            if path[0] == 'L':
                node = node.left
            else:
                node = node.right
            path = path[1:]
        return node

 

posted @ 2018-09-13 15:00  seyjs  阅读(168)  评论(0编辑  收藏  举报