二叉树相关
102.二叉树的层序遍历
参考文章
题目链接
个人题解
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) {
return res;
}
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
List<Integer> temp = new ArrayList<>();
int len = queue.size();
while (len > 0) {
TreeNode tempNode = queue.poll();
temp.add(tempNode.val);
if (tempNode.left != null) {
queue.offer(tempNode.left);
}
if (tempNode.right != null) {
queue.offer(tempNode.right);
}
len--;
}
res.add(temp);
}
return res;
}
}
226.翻转二叉树
参考文章
题目链接
个人题解
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
ArrayDeque<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
while (!queue.isEmpty()) {
int len = queue.size();
while (len > 0) {
TreeNode tempNode = queue.poll();
TreeNode temp = tempNode.left;
tempNode.left = tempNode.right;
tempNode.right = temp;
if (tempNode.left != null) {
queue.offer(tempNode.left);
}
if (tempNode.right != null) {
queue.offer(tempNode.right);
}
len--;
}
}
return root;
}
public void swap(TreeNode root) {
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
}
101. 对称二叉树
参考文章
题目链接
个人题解
class Solution {
public boolean isSymmetric(TreeNode root) {
return compare(root.left, root.right);
}
private boolean compare(TreeNode left, TreeNode right) {
if (left == null && right != null) {
return false;
}
if (left != null && right == null) {
return false;
}
if (left == null && right == null) {
return true;
}
if (left.val != right.val) {
return false;
}
boolean compareOut = compare(left.left, right.right);
boolean compareIn = compare(left.right, right.left);
return compareOut && compareIn;
}
}