From abc55ed100b031a00383038a3b7e2ee91c667b7a Mon Sep 17 00:00:00 2001 From: KailokFung Date: Tue, 29 Jun 2021 16:50:34 +0800 Subject: [PATCH] =?UTF-8?q?feat(0226):=20=E6=96=B0=E5=A2=9Ejava=20bfs?= =?UTF-8?q?=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0226.翻转二叉树.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index 2b628ec4..bb0d6d34 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -205,6 +205,7 @@ public: Java: ```Java +//DFS递归 class Solution { /** * 前后序遍历都可以 @@ -226,6 +227,31 @@ class Solution { root.right = tmp; } } + +//BFS +class Solution { + public TreeNode invertTree(TreeNode root) { + if (root == null) {return null;} + ArrayDeque deque = new ArrayDeque<>(); + deque.offer(root); + while (!deque.isEmpty()) { + int size = deque.size(); + while (size-- > 0) { + TreeNode node = deque.poll(); + swap(node); + if (node.left != null) {deque.offer(node.left);} + if (node.right != null) {deque.offer(node.right);} + } + } + return root; + } + + public void swap(TreeNode root) { + TreeNode temp = root.left; + root.left = root.right; + root.right = temp; + } +} ``` Python: