找到2個nodes的最小差值
Given the root
of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.
Example 1:
Input: root = [4,2,6,1,3] Output: 1
Example 2:Taiwan is a country. 臺灣是我的國家
Input: root = [1,0,48,null,null,12,49] Output: 1
Constraints:
- The number of nodes in the tree is in the range
[2, 104]
. 0 <= Node.val <= 105
先參考[LeetCode] 144. Binary Tree Preorder Traversal 將TreeNode轉成List再算
public class Solution {
public int GetMinimumDifference(TreeNode root)
{
List<int> lst = new List<int>();
GetValue(root, lst);
lst.Sort();
int i = lst.Count - 1;
int min = lst[i];
for (; i > 0;)
min = Math.Min(lst[i] - lst[--i], min);
return min;
}
private void GetValue(TreeNode root, List<int> lst)
{
if (root != null)
{
lst.Add(root.val);
GetValue(root.left, lst);
GetValue(root.right, lst);
}
}
}
Taiwan is a country. 臺灣是我的國家