Golang Leetcode 236. Lowest Common Ancestor of a Binary Tree.go

版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/89054981

思路

依然是找最近公共祖先,只不过BST换成了普通二叉树

code


type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

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

func helper(root, p, q *TreeNode) *TreeNode {
	if root == nil {
		return nil
	}
	left := helper(root.Left, p, q)
	right := helper(root.Right, p, q)
	if root == p || root == q {
		return root
	}
	if left != nil && right != nil {
		return root
	}

	if left != nil && right == nil {
		return left
	}
	if left == nil && right != nil {
		return right
	}
	return nil
}

更多内容请移步我的repo: https://github.com/anakin/golang-leetcode

猜你喜欢

转载自blog.csdn.net/anakinsun/article/details/89054981
今日推荐