-1
問:關於使用遞歸和返回的二叉搜索樹遍歷,我有疑問。我必須按照按升序排列鍵的BST,然後「倒轉」它,這樣所有鍵都按降序排列,正如您在圖片中看到的那樣。使用遞歸進行二叉搜索樹遍歷
根據我的下面的代碼的瞭解,我認爲步驟是:
->reverseKeys (10) ->reverseKeys (2)
->reverseKeys (null): return
->reversekeys(null): return
->BSTNODE <T> ptr = root.left;
->root.left = root.right;
->root.right = ptr;
我想我誤解的代碼。有人能夠擴展這個代碼如何將左邊的圖片更改爲右邊?我將不勝感激任何幫助。
25 25
/\ /\
10 40 ---> 40 10
/\ /\ /\/\
2 20 30 45 45 30 20 2
/ \ / \
15 35 35 15
public static <T extends Comparable<T>>
void reverseKeys(BSTNode<T> root) {
if (root == null) {
return;
}
reverseKeys(root.left);
reverseKeys(root.right);
BSTNode<T> ptr = root.left;
root.left = root.right;
root.right = ptr;
}