530. 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.


题目本身很简单,涉及到了二叉树的遍历,就在这里总结一下。
二叉树遍历方法有前序遍历,中序遍历,后序遍历,层遍历以及深度优先搜索和广度优先搜索等。并且还分迭代和递归两种版本,前三种遍历的特点如下:

  • 先序遍历:在第一次遍历到节点时就执行操作,一般只是想遍历执行操作(或输出结果)可选用先序遍历;
  • 中序遍历:对于二分搜索树,中序遍历的操作顺序(或输出结果顺序)是符合从小到大(或从大到小)顺序的,故要遍历输出排序好的结果需要使用中序遍历
  • 后序遍历:后续遍历的特点是执行操作时,肯定已经遍历过该节点的左右子节点,故适用于要进行破坏性操作的情况,比如删除所有节点

作者:Entronad
链接:https://www.zhihu.com/question/22031935/answer/153859490
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

层次遍历,即按树的层来遍历数据,主要是利用了队列(先先进先出)的方法。

广度优先搜索BFS和深度优先搜索DFS主要是利用了图的思想,毕竟树结构就是一个每个节点的有两条路的图,因此图的方法肯定适合于树。同理在之前也提到HashMap的思想也同样适用于数组。

值得注意的是,在迭代版本中的前中后序遍历比较简单,而在循环版本里面的前中后序方法虽然都使用了栈STACK,但是并不相同,值得好好研究。详见上面的二叉树遍历方法链接。

程序如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int diff = Integer.MAX_VALUE;
    int pre;
    int cur;
    public int getMinimumDifference(TreeNode root) {
        pre = Integer.MAX_VALUE;
        find(root);
        return diff;
    }
    public void find(TreeNode root){
        if(root == null)
            return;
        find(root.left);
        cur = root.val;
        diff = Math.min(diff, Math.abs(cur-pre));
        pre = root.val;
        find(root.right);
    }
}

猜你喜欢

转载自blog.csdn.net/timemagician/article/details/79093973