文章目錄
- 題目
- 分析
- 代碼
題目
操作給定的二叉樹,將其變換為源二叉樹的鏡像,
二叉樹的鏡像定義:源二叉樹
8
/ \
6 10
/ \ / \
5 7 9 11
鏡像二叉樹
8
/ \
10 6
/ \ / \
11 9 7 5
分析
遞回交換左右子樹即可
1、root == null直接回傳
2、沒有左右子樹時就不用繼續進行root.left == null && root.right == null
3、左右子樹至少有一個存在
- 左右子樹都不為空則交換左右子樹
- 左子樹為空右子樹不為空則把右子樹掛到左子樹然后把右子樹置為空即可
- 右子樹為空左子樹不為空則把左子樹掛到右子樹然后把左子樹置為空即可


代碼
public void Mirror(TreeNode root) {
if (root == null||(root.left == null && root.right == null)) return;
if (root.right != null && root.left != null) {//左右子樹都不為空則交換左右子樹
TreeNode node = null;
node = root.right;
root.right = root.left;
root.left = node;
} else if (root.right != null && root.left == null) {//左邊為空,右邊不為空
root.left = root.right;
root.right = null;
} else {//左邊為空,右邊不為空
root.right = root.left;
root.left = null;
}
if(root.left!=null)Mirror(root.left);
if(root.right!=null)Mirror(root.right);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/256412.html
標籤:其他
上一篇:一文搞懂Linux行程調度原理
