Leetcode - unique-binary-search-trees
Leetcode - Longest Increasing Subsequence

Leetcode - lowest-common-ancestor-of-a-binary-tree

violet posted @ Mar 20, 2020 03:46:03 AM in 算法 with tags Algorithm Golang tree , 180 阅读

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/

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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given the following binary tree:  root = [3,5,1,6,2,0,8,null,null,7,4]


 

func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
   return find(root, p, q)
}

func find(root, p, q *TreeNode) *TreeNode {
    if root == nil {
        return root
    }
    if root.Val == p.Val || root.Val == q.Val {
        return root
    }
    leftLA := find(root.Left, p, q)
    rightLA := find(root.Right, p, q)
    if leftLA != nil && rightLA != nil {
        return root
    }
    
    if leftLA != nil {
        return leftLA
    }
    
    return rightLA
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter