530. 二叉搜索树的最小绝对差 给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值. 示例: 输入: 1 \ 3 / 2 输出: 1 解释: 最小绝对差为 1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3). PS: 递归遍历 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; *…
Leetcode:530. 二叉搜索树的最小绝对差 Leetcode:530. 二叉搜索树的最小绝对差 Talk is cheap . Show me the code . /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {}…
题目230. 二叉搜索树中第K小的元素 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素. 题解 中序遍历BST,得到有序序列,返回有序序列的k-1号元素. 代码 class Solution { public int kthSmallest(TreeNode root, int k) { List<Integer> list = new LinkedList<>(); inorder(root,list); return list.get(…
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…
给定一个所有节点为非负值的二叉搜索树,求树中任意两节点的差的绝对值的最小值.示例 :输入:   1    \     3    /   2输出:1解释:最小绝对差为1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3).注意: 树中至少有2个节点.详见:https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/ C++: 方法一: /** * Definition for a binary tr…
①题目 给定一个所有节点为非负值的二叉搜索树,求树中任意两节点的差的绝对值的最小值. 示例 : 输入: 1   \   3  / 2 输出:1 解释:最小绝对差为1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3).注意: 树中至少有2个节点. ②思路 这个题我自己没做出来,所以看了别人的题解. 思路就是,使用中序遍历,在中序遍历的同时,计算差值. ③代码 class Solution { TreeNode pre; int res = Integer.MAX_VALUE; //res是…
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…
题目 又是常见的BST,要利用BST的性质,即中序遍历是有序递增序列. 法一.中序遍历 1 class Solution { 2 public: 3 vector<int>res; 4 void InOrder(TreeNode* p){ 5 if(p!=NULL){ 6 InOrder(p->left); 7 res.push_back(p->val); 8 InOrder(p->right); 9 } 10 } 11 int getMinimumDifference(Tr…
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has…
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has…