flag
软件学院大三党,每天一道算法题,第35天
题目介绍
给定一个所有节点为非负值的二叉搜索树,求树中任意两节点的差的绝对值的最小值。
背景知识
二叉搜索(排序)树或者是一棵空树,或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
(4)没有键值相等的节点
通过中序遍历二叉搜索树得到的关键码序列是一个递增序列。 这是二叉搜索树的一个重要性质
思路
中序遍历
递归:
public static void midOrderRe(TreeNode biTree)
{//中序遍历递归实现
if(biTree == null)
return;
else
{
midOrderRe(biTree.left);
System.out.println(biTree.value);
midOrderRe(biTree.right);
}
}
非递归:
采用栈
public static void midOrder(TreeNode biTree)
{//中序遍历费递归实现
Stack<TreeNode> stack = new Stack<TreeNode>();
while(biTree != null || !stack.isEmpty())
{
while(biTree != null)
{
stack.push(biTree);
biTree = biTree.left;
}
if(!stack.isEmpty())
{
biTree = stack.pop();
System.out.println(biTree.value);
biTree = biTree.right;
}
}
关键代码
递归:
TreeNode pre = null;
int res = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
inOrder(root);
return res;
}
public void inOrder(TreeNode root) {
if(root == null) {
return;
}
inOrder(root.left);
if(pre != null) {
res = Math.min(res, root.val - pre.val);
}
pre = root;
inOrder(root.right);
}
非递归:
public int getMinimumDifference(TreeNode root){
int min=Integer.MAX_VALUE;
int lastVal=Integer.MIN_VALUE;
Stack<TreeNode>stack=new Stack<>();
while (root!=null||!stack.isEmpty()){
while (root!=null){
stack.push(root);
root=root.left;
}
if(!stack.isEmpty()){
root=stack.pop();
if(lastVal!=Integer.MIN_VALUE){
min=Math.min(min,root.val-lastVal);
}
lastVal=root.val;
root=root.right;
}
}
return min;
}
总结
相比之下递归的效率更高,但是代码书写难度比较大