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

2019-04-12 11:36:45 浏览数 (1)

版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412923

思路

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

code

代码语言:javascript复制
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
}

0 人点赞