lintcode 1033. BST中的最小差值

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

样例
样例1:

输入: root = {4,2,6,1,3,#,#}
输出: 1
解释:
请留意,root是一个树节点的结构,而非一个普通数组。

给定的树{4,2,6,1,3,#,#}的样子如下图:

          4
        /   \
      2      6
     / \    
    1   3  

在这棵树中,最小数值差距为 1, 它出现在node 1 与 node 2 之间, 也同时存在 node 3 与 node 2之间
样例2:

输入: root = {5,1,8}
输出: 3
解释:
请留意,root是一个树节点的结构,而非一个普通数组。

给定的树{5,1,8}的样子如下图:

     5
   /   \
 1      8
 
在这棵树中,最小数值差距为 3, 它出现在node 5与node 8之间.
注意事项
1.这棵二叉搜索树的大小在 2 到100之间。
2.这棵二叉搜索树是存在的,每个点的数值是一个整数,而且每个点的数值将会是不同的。
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: the root
     * @return: the minimum difference between the values of any two different nodes in the tree
     */
    int minDiffInBST(TreeNode * root) {
        // Write your code here  
        recursion(root);
        int res=tmp[1]-tmp[0];
        for (int i = 1; i < tmp.size(); i++) {
            /* code */
            res=res<tmp[i]-tmp[i-1]?res:tmp[i]-tmp[i-1];
        }
        return res;
    }
    void recursion(TreeNode*root)
    {
        if(root==NULL) return;
        if(root->left)recursion(root->left);
        tmp.push_back(root->val);
        if(root->right)recursion(root->right);
    }
   std::vector<int> tmp;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值