Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

二叉搜索树节点最小距离 #132

Open
yankewei opened this issue Apr 13, 2021 · 1 comment
Open

二叉搜索树节点最小距离 #132

yankewei opened this issue Apr 13, 2021 · 1 comment
Labels
题目类型为树结构 深度优先搜索 题目包含深度优先搜索解法 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。

注意:本题与 530:https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/ 相同

示例 1:

示例1

输入:root = [4,2,6,1,3]
输出:1

示例 2:

示例2

输入:root = [1,0,48,null,null,12,49]
输出:1

提示:

  • 树中节点数目在范围 [2, 100] 内
  • 0 <= Node.val <= 105

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei yankewei added 简单 题目难度为简单 深度优先搜索 题目包含深度优先搜索解法 labels Apr 13, 2021
@yankewei
Copy link
Owner Author

dfs

因为是一个二叉搜索树,可以直接中序遍历获取排序后的结果

func minDiffInBST(root *TreeNode) int {
    var slice []int
    var dfs func(root *TreeNode)
    dfs = func (root *TreeNode) {
	if root == nil {
	    return
	}
	dfs(root.Left)
	slice = append(slice, root.Val)
	dfs(root.Right)
    }
    dfs(root)
    ret := math.MaxInt64
    for i := 0; i < len(slice)-1; i++ {
	if slice[i+1] - slice[i] < ret {
	    ret = slice[i+1] - slice[i]
	}
    }
    return ret
}

@yankewei yankewei added the 题目类型为树结构 label Apr 13, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
题目类型为树结构 深度优先搜索 题目包含深度优先搜索解法 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant