iT邦幫忙

2025 iThome 鐵人賽

DAY 10
0
自我挑戰組

LeetCode 每日任務系列 第 10

LeetCode Day10

  • 分享至 

  • xImage
  •  

226.Invert Binary Tree

BFS(廣度優先搜尋)

題目:
將給定的二元樹進行反轉,也就是將每個節點的左子樹和右子樹交換,然後返回新的根節點

範例:

  • Example 1:
    Input: root = [4,2,7,1,3,6,9]
    Output: [4,7,2,9,6,3,1]

  • Example 2:
    Input: root = [2,1,3]
    Output: [2,3,1]

  • Example 3:
    Input: root = []
    Output: []

想法:

  • 使用 BFS 進行層級遍歷
  • 先將根節點加入佇列
  • 每次從佇列取出一個節點,交換它的左、右子樹
  • 如果該節點的左右子節點存在,就將它們加入佇列
  • 直到佇列為空,遍歷結束,返回修改後的根節點

程式碼:

class TreeNode {
	int val;
	TreeNode left;
	TreeNode right;
	TreeNode() {}
	TreeNode(int val) { this.val = val; }
	TreeNode(int val, TreeNode left, TreeNode right) {
		this.val = val;
		this.left = left;
		this.right = right;
	}
}

class Solution {
	public TreeNode invertTree(TreeNode root) {
		if (root == null) {
			return null;
		}

		Queue<TreeNode> queue = new LinkedList<>();
		queue.offer(root);

		while (!queue.isEmpty()) {
			TreeNode node = queue.poll();

			// 交換左右子節點
			TreeNode temp = node.left;
			node.left = node.right;
			node.right = temp;

			// 將子節點加入佇列
			if (node.left != null) {
				queue.offer(node.left);
			}
			if (node.right != null) {
				queue.offer(node.right);
			}
		}
		return root;
	}
}


實際操作:
https://ithelp.ithome.com.tw/upload/images/20250924/20170015oboCWqjvCR.png
queue = [4]

STEP1
poll() = 4
swap → 左右互換
https://ithelp.ithome.com.tw/upload/images/20250924/20170015OJKiB8w89s.png
加入 queue: [7, 2]

STEP2
poll() = 7
swap → 左右互換(但 7 沒子樹,不變)
queue = [2]

STEP3
poll() = 2
swap → 左右互換(但 2 沒子樹,不變)
queue = []

https://ithelp.ithome.com.tw/upload/images/20250924/20170015tF9m53jXur.png


上一篇
LeetCode Day9
下一篇
LeetCode Day11
系列文
LeetCode 每日任務12
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言