102. 二叉树的层序遍历 226.翻转二叉树 101. 对称二叉树
102. 二叉树的层序遍历
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) return result;
queue.offer(root);
while (!queue.isEmpty()){
int size = queue.size();
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < size; i++) {
TreeNode tmpNode = queue.poll();
list.add(tmpNode.val);
if (tmpNode.left != null) queue.offer(tmpNode.left);
if (tmpNode.right != null) queue.offer(tmpNode.right);
}
result.add(list);
}
return result;
}
}
226.翻转二叉树
class Solution {
public TreeNode invertTree(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
if (root == null) return root;
queue.offer(root);
while (!queue.isEmpty()){
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode tmpNode = queue.poll();
swap(tmpNode);
if (tmpNode.left != null) queue.offer(tmpNode.left);
if (tmpNode.right != null) queue.offer(tmpNode.right);
}
}
return root;
}
public void swap(TreeNode root){
TreeNode temp = root.right;
root.right = root.left;
root.left = temp;
}
}
101. 对称二叉树
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) return false;
return compare(root.left, root.right);
}
public boolean compare(TreeNode node1, TreeNode node2){
if (node1 == null && node2 != null) {
return false;
}
if (node1 != null && node2 == null) {
return false;
}
if (node1 == null && node2 == null) {
return true;
}
if (node1.val != node2.val) return false;
boolean compareOutside = compare(node1.left, node2.right);
// 比较内侧
boolean compareInside = compare(node1.right, node2.left);
return compareInside && compareOutside;
}
}
总结
层次遍历很重要!!! 递归学的不好