leetcode Minimum Absolute Difference in BST 二叉搜索树中的最小差
来源:互联网 发布:c语言while是什么意思 编辑:程序博客网 时间:2024/06/16 03:56
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Note: There are at least two nodes in this BST.
题意:求二叉搜索树中节点值的最小差。
思路:二叉搜索树的左子节点比根节点小,右子节点比根节点大,注意左子节点的右子节点比根节点小,且其与根节点的差值比左子节点和根节点的差值小,右子节点同理。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution { int min_dif = INT_MAX, val = -1;public: int getMinimumDifference(TreeNode* root) { //先求左子树最小差值 if (root->left != NULL) getMinimumDifference(root->left); if (val >= 0) min_dif = min(min_dif, root->val - val); //记录当前根节点值 val = root->val; if (root->right != NULL) getMinimumDifference(root->right); return min_dif; }};
阅读全文
0 0
- leetcode Minimum Absolute Difference in BST 二叉搜索树中的最小差
- 530. Minimum Absolute Difference in BST二叉搜索树
- [LeetCode]530. Minimum Absolute Difference in BST(BST的最小绝对差)
- 算法题——Minimum Absolute Difference in BST(JAVA)二叉搜索树
- Leetcode-530. Minimum Absolute Difference in BST
- LeetCode: 503.Minimum Absolute Difference in BST
- 【Leetcode】530. Minimum Absolute Difference in BST
- Leetcode 530. Minimum Absolute Difference in BST
- Leetcode #530 Minimum Absolute Difference in BST
- [leetcode] 530. Minimum Absolute Difference in BST
- LeetCode-530. Minimum Absolute Difference in BST
- LeetCode 530. Minimum Absolute Difference in BST
- [LeetCode]530. Minimum Absolute Difference in BST
- Leetcode 530 Minimum Absolute Difference in BST
- leetcode-Minimum Absolute Difference in BST
- LeetCode | 530. Minimum Absolute Difference in BST
- leetcode 530. Minimum Absolute Difference in BST
- [leetcode]-530. Minimum Absolute Difference in BST
- [BZOJ]4753: [Jsoi2016]最佳团体 01分数规划+树形DP
- 三.java多线程之线程调度
- redis数据丢失及解决
- 4.go开源groupcache项目笔记——关于strconv
- RESTful API设计指南
- leetcode Minimum Absolute Difference in BST 二叉搜索树中的最小差
- Milking Time POJ
- 1022. D进制的A+B (20)
- 关于二叉树的结点
- 5.go开源groupcache项目笔记——关于testing
- Github .gitignore详解
- 【数位DP】F(x) HDU
- 使用C语言编写程序,计算N个整数的和(随机输入一个值,例如1到100之间所有整数的和)
- Java JUC之Atomic系列12大类实例讲解和原理分解