LeetCode-Minimum_Absolute_Difference_in_BST

題目:

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

Example:

Input:

   1
    \
     3
    /
   2

Output:
1

Explanation:
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.


翻譯:

給定一個沒有負值的二叉搜索樹,找到任何兩個節點的最小的絕對差。

例子:

輸入:

   1
    \
     3
    /
   2

輸出:
1

解釋:
最小的絕對差是1,是2和1之間的絕對差(或2和3之間)。


注意: BST中最少由兩個節點。


思路:參照https://www.cnblogs.com/grandyang/p/6540165.html

由於BST中,左<根<右,那麼最小絕對差在左節點和父節點之間或父節點和右節點之間。所以對BST進行中序遍歷,然後當前節點值和之前節點值求絕對差並更新結果res。對於沒有的節點,用pre=-1來計算。


C++代碼(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <algorithm>
using namespace std;

struct TreeNode {
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
	int getMinimumDifference(TreeNode* root) {
		int res = INT_MAX, pre = -1;
		inorder(root, pre, res);
		return res;
	}
	void inorder(TreeNode* node, int& pre, int& res) {
		if (!node) return;
		inorder(node->left, pre, res);
		if (pre != -1) res = min(res, node->val - pre);
		pre = node->val;
		inorder(node->right, pre, res);
	}
};

int main()
{
	Solution s;
	TreeNode* root = new TreeNode(1);
	root->right = new TreeNode(3);
	root->right->left = new TreeNode(2);
	int result = s.getMinimumDifference(root);
	cout << result<<endl;
    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章