博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 530. Minimum Absolute Difference in BST | inorder
阅读量:6757 次
发布时间:2019-06-26

本文共 1929 字,大约阅读时间需要 6 分钟。

Description

Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

Example:Input:   1    \     3    /   2Output:1Explanation:The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).Note: There are at least two nodes in this BST.

Discuss

C++ 7 lines, O(n) run-time O(h) memory

In-order traversal of BST yields sorted sequence. So, we just need to subtract the previous element from the current one, and keep track of the minimum. We need O(1) memory as we only store the previous element, but we still need O(h) for the stack.

  • 参数在inorder()里面传递
void inorderTraverse(TreeNode* root, int& val, int& min_dif) {    if (root->left != NULL) inorderTraverse(root->left, val, min_dif);    if (val >= 0) min_dif = min(min_dif, root->val - val);    val = root->val;    if (root->right != NULL) inorderTraverse(root->right, val, min_dif);}int getMinimumDifference(TreeNode* root) {    auto min_dif = INT_MAX, val = -1;    inorderTraverse(root, val, min_dif);    return min_dif;}// 下面code为我据此重写的inorder, 细节略有区别class Solution {private:    void inorder(TreeNode *root, int &pre, int &minval) {        if (!root) return;        inorder(root->left, pre, minval);        /* 以下为visit 部分 */        if (pre >= 0) minval = min(minval, root->val - pre);        pre = root->val;        /* 以上 */        inorder(root->right, pre, minval);    }public:    int getMinimumDifference(TreeNode *root) {        int pre = -1, minval = 99999;        inorder(root, pre, minval);        return minval;    }};
  • 参数在外 | member variables
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;}

转载地址:http://fzzeo.baihongyu.com/

你可能感兴趣的文章
POJ-2236-Wireless Network
查看>>
ASP.NET引用母版页属性的问题
查看>>
JavaScript 模块模式
查看>>
链接返回上级或事件返回上级
查看>>
ROS学习之catkin_make
查看>>
Android中的颜色值RGB对照表表
查看>>
css单位
查看>>
jquery.validate remote BUG
查看>>
一百元的智能家居——Asp.Net Mvc Api+讯飞语音+Android+Arduino
查看>>
C/C++变量命名规则
查看>>
pandas安装及使用
查看>>
Linux SHELL if 命令参数说明
查看>>
Python的构造函数和析构函数,对象和类的变量不一样
查看>>
window常用的『运行』命令
查看>>
3G中的A-GPS移动定位技术
查看>>
java第五章:面向对象(oop)
查看>>
Maze
查看>>
激光炸弹
查看>>
9.23 模拟赛
查看>>
static_cast、dynamic_cast、const_cast和reinterpret_cast总结
查看>>