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;
}
總結
相比之下遞歸的效率更高,但是代碼書寫難度比較大