4.算法通关面试 --- 树和图

1.验证二叉搜索树
https://leetcode-cn.com/problems/validate-binary-search-tree/

1.用中序遍历,如果结果是升序的,那就是二叉排序树

func isValidBST(root *TreeNode) bool {
	stack := []*TreeNode {}
	inorder := math.MinInt64

	for len(stack) > 0 || root != nil {
		for root != nil {
			stack = append(stack, root)
			root = root.Left
		}

		root = stack[len(stack) - 1]
		stack = stack[:len(stack) - 1]

		if root.Val <= inorder {
			return false
		}

		inorder = root.Val
		root = root.Right
	}

	return  true
}


2.递归函数判断

func isValidBST(root *TreeNode) bool {
	return helper(root, math.MinInt64, math.MaxInt64)
}

func helper(root *TreeNode, lower, upper int) bool {
	if root == nil {
		return true
	}

	if root.Val <= lower || root.Val >= upper {
		return false
	}

	return helper(root.Left, lower, root.Val) && helper(root.Right, root.Val, upper)
}

2.二叉搜索树的最近公共祖先
https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

1.路径查找

func getPath(root, target *TreeNode) (path []*TreeNode) {
	node := root

	for node != target {
		path = append(path, node)

		if target.Val < node.Val {
			node = node.Left
		} else {
			node = node.Right
		}
	}

	path = append(path, node)

	return
}

func lowestCommonAncestor(root, p, q *TreeNode) (ancestor *TreeNode) {
	pathP := getPath(root, p)
	pathQ := getPath(root, q)

	for i := 0; i < len(pathP) && i < len(pathQ) && pathP[i] == pathQ[i]; i++ {
		ancestor = pathP[i]
	}

	return
}

3.二叉树的最近公共祖先
https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/

二叉树的遍历:

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值