mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
feat(0226): 新增java bfs写法
This commit is contained in:
@ -205,6 +205,7 @@ public:
|
|||||||
Java:
|
Java:
|
||||||
|
|
||||||
```Java
|
```Java
|
||||||
|
//DFS递归
|
||||||
class Solution {
|
class Solution {
|
||||||
/**
|
/**
|
||||||
* 前后序遍历都可以
|
* 前后序遍历都可以
|
||||||
@ -226,6 +227,31 @@ class Solution {
|
|||||||
root.right = tmp;
|
root.right = tmp;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//BFS
|
||||||
|
class Solution {
|
||||||
|
public TreeNode invertTree(TreeNode root) {
|
||||||
|
if (root == null) {return null;}
|
||||||
|
ArrayDeque<TreeNode> 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:
|
Python:
|
||||||
|
Reference in New Issue
Block a user