lowest common acestor

This commit is contained in:
ehlxr 2022-06-19 21:58:38 +08:00
parent 80212df249
commit 23be3094f9
4 changed files with 98 additions and 0 deletions

View File

@ -0,0 +1,49 @@
package src
// 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先
// 对于有根树 T 的两个节点 p、q最近公共祖先表示为一个节点 x
// 满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
return find(root, p.Val, q.Val)
}
func find(root *TreeNode, l, r int) *TreeNode {
if root == nil {
return nil
}
if root.Val == l || root.Val == r {
return root
}
left := find(root.Left, l, r)
right := find(root.Right, l, r)
if left != nil && right != nil {
return root
}
if left == nil {
return right
}
return left
}
// func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
// if root == nil {
// return nil
// }
// // p 和 q 均存在于给定的二叉树中
// if root.Val == p.Val || root.Val == q.Val {
// return root
// }
//
// left := lowestCommonAncestor(root.Left, p, q)
// right := lowestCommonAncestor(root.Right, p, q)
// if left != nil && right != nil {
// return root
// }
//
// if left != nil {
// return left
// }
// return right
// }

View File

@ -0,0 +1,25 @@
package src
import (
"fmt"
"testing"
)
func TestLowestCommonAncestor(t *testing.T) {
// 初始化二叉树
root := &TreeNode{Val: 3}
root.Left = &TreeNode{Val: 5}
root.Right = &TreeNode{Val: 1}
root.Left.Left = &TreeNode{Val: 6}
root.Left.Right = &TreeNode{Val: 2}
root.Right.Left = &TreeNode{Val: 7}
root.Right.Right = &TreeNode{Val: 4}
fmt.Printf("lowestCommonAncestor of %d and %d is %+v \n", 5, 1, lowestCommonAncestor(root, &TreeNode{Val: 5}, &TreeNode{Val: 1}).Val)
fmt.Printf("lowestCommonAncestor of %d and %d is %+v \n", 5, 4, lowestCommonAncestor(root, &TreeNode{Val: 5}, &TreeNode{Val: 4}).Val)
fmt.Printf("lowestCommonAncestor of %d and %d is %+v \n", 2, 6, lowestCommonAncestor(root, &TreeNode{Val: 2}, &TreeNode{Val: 6}).Val)
fmt.Printf("lowestCommonAncestor of %d and %d is %+v \n", 2, 7, lowestCommonAncestor(root, &TreeNode{Val: 2}, &TreeNode{Val: 7}).Val)
fmt.Printf("lowestCommonAncestor of %d and %d is %+v \n", 2, 4, lowestCommonAncestor(root, &TreeNode{Val: 2}, &TreeNode{Val: 4}).Val)
fmt.Printf("lowestCommonAncestor of %d and %d is %+v \n", 2, 3, lowestCommonAncestor(root, &TreeNode{Val: 2}, &TreeNode{Val: 3}).Val)
fmt.Printf("lowestCommonAncestor of %d and %d is %+v \n", 2, 1, lowestCommonAncestor(root, &TreeNode{Val: 2}, &TreeNode{Val: 1}).Val)
}

View File

@ -13,3 +13,16 @@ func (n *ListNode) String() string {
}
return fmt.Sprintf("{Val:%d Next:%+v}", n.Val, *n.Next)
}
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func (n *TreeNode) String() string {
if n == nil {
return "nil"
}
return fmt.Sprintf("{Val:%d Left:%+v Right:%+v}", n.Val, *n.Left, *n.Right)
}

11
src/palindrome_test.go Normal file
View File

@ -0,0 +1,11 @@
package src
import (
"fmt"
"testing"
)
func TestLongestPalindrome(t *testing.T) {
s := "babad"
fmt.Printf("LongestPalindrome of %s is %s\n", s, LongestPalindrome(s))
}