問題描述:java
輸入一顆二元查找樹,將該樹轉換爲它的鏡像樹,即對每個節點,互換左右子樹。spa
例如輸入:code
6
/ \
4 12
/ \ / \
2 5 8 16orm
輸出:it
6
/ \
12 4
/ \ / \
16 8 5 2class
分析:
定義二叉查找樹節點:margin
class BSTreeNode{ BSTreeNode(int x, BSTreeNode lt, BSTreeNode rt){ value = x; left = lt; right = rt; } int value; BSTreeNode left; BSTreeNode right; }
代碼實現:top
public void mirrorChange(){ mirrorChange(root); } public void mirrorChange(BSTreeNode n){ if(n == null){ return; } if(n.left != null){ mirrorChange(n.left); } if(n.right != null){ mirrorChange(n.right); } BSTreeNode tmp = n.left; n.left = n.right; n.right = tmp; }