102. 二叉树的层序遍历
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
List<List<Integer>> listList = new ArrayList<>();
TreeNode cur = root;
if (cur == null) {
return listList;
}
queue.offer(cur);
int len;
while (!queue.isEmpty()) {
len = queue.size();
List<Integer> list = new ArrayList<>();
while (len > 0) {
cur = queue.poll();
list.add(cur.val);
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
len--;
}
listList.add(list);
}
return listList;
}
}
226. 翻转二叉树
class Solution {
public TreeNode invertTree(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
TreeNode cur = root;
if (cur == null) {
return cur;
}
queue.offer(cur);
int len;
while (!queue.isEmpty()) {
len = queue.size();
int size = len;
while (len > 0) {
cur = queue.poll();
swap(cur);
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
len--;
}
}
return root;
}
public void swap(TreeNode treeNode) {
TreeNode node;
node = treeNode.left;
treeNode.left = treeNode.right;
treeNode.right = node;
}
}
101. 对称二叉树
class Solution {
public boolean isSymmetric(TreeNode root) {
return compare(root.left,root.right );
}
public boolean compare(TreeNode left, TreeNode right) {
boolean bool1=false;
if (left == null && right == null) {
return true;
}
// 有了上面的判断, 就可以保证可不能是两个null,
// 这样下面,只要有null,就一定是只有一个null
if (left == null || right == null) {
return false;
}
if (left.val == right.val) {
bool1 = true;
}
boolean bool2 = compare(left.left, right.right);
boolean bool3 = compare(left.right, right.left);
return bool1 & bool2 & bool3;
}
}
标签:10,right,TreeNode,cur,层序,queue,道题,null,left
From: https://www.cnblogs.com/Chain-Tian/p/17004853.html