一、层序遍历 10
思路:借助队列将每一层的节点放进队列,出队的时候如果左右孩子不为空,则加入队列。
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Deque<TreeNode> deque = new LinkedList<>();
List<List<Integer>> result = new ArrayList<>();
if(root == null) {
return result;
}
deque.offer(root);
while(!deque.isEmpty()) {
List<Integer> list = new ArrayList<>();
int len = deque.size();
while(len-- > 0) {
TreeNode temp = deque.poll();
list.add(temp.val);
if(temp.left != null) deque.offer(temp.left);
if(temp.right != null) deque.offer(temp.right);
}
result.add(list);
}
return result;
}
}
二、226.翻转二叉树
思路:首先想的的方法是递归翻转每个节点的左右孩子,按照三部曲编写代码,单层逻辑只需要简单交换当前节点的左右孩子,然后按照前序遍历的递归顺序进行递归。
class Solution {
public TreeNode invertTree(TreeNode root) {
invert(root);
return root;
}
private void invert(TreeNode node) {
if(node == null) return;
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
invert(node.left);
invert(node.right);
}
}
//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;
}
三、101.对称二叉树 2
思路:利用了双端队列,将一层的节点先放入队列之中,从队列的左边取出节点和队列从右边取出的节点进行比较,进而判断二叉树是否对称。
class Solution {
public boolean isSymmetric(TreeNode root) {
Deque<TreeNode> deque = new LinkedList<>();
if(root == null) return false;
deque.offerFirst(root.left);
deque.offerLast(root.right);
while(!deque.isEmpty()) {
TreeNode leftNode = deque.pollFirst();
TreeNode rightNode = deque.pollLast();
if (leftNode == null && rightNode == null) {
continue;
}
if (leftNode == null || rightNode == null || leftNode.val != rightNode.val) {
return false;
}
deque.offerFirst(leftNode.left);
deque.offerFirst(leftNode.right);
deque.offerLast(rightNode.right);
deque.offerLast(rightNode.left);
}
return true;
}
}