My LeetCode Diary - Day15 BinaryTree
102. Binary Tree Level Order Traversal
Link
class Solution {
public List<List<Integer>> resList = new ArrayList<List<Integer>>();
public List<List<Integer>> levelOrder(TreeNode root) {
checkFun(root);
return resList;
}
public void checkFun(TreeNode node) {
if (node == null) {
return;
}
Queue<TreeNode> que = new LinkedList<TreeNode>();
que.offer(node);
while(!que.isEmpty()) {
List<Integer> itemList = new ArrayList<>();
int len = que.size();
while (len>0) {
TreeNode tmpNode = que.poll();
itemList.add(tmpNode.val);
if (tmpNode.left != null) {
que.offer(tmpNode.left);
}
if (tmpNode.right != null) {
que.offer(tmpNode.right);
}
len--;
}
resList.add(itemList);
}
}
}
226. Invert Binary Tree
Link
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
invertTree(root.left);
invertTree(root.right);
swapChildren(root);
return root;
}
private void swapChildren(TreeNode root) {
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
}
}
101. Symmetric Tree
Link
class Solution {
private boolean isEquivalent(TreeNode left, TreeNode right) {
if (left==null || right==null) return left == right;
else return left.val == right.val && isEquivalent(left.left, right.right) && isEquivalent(left.right, right.left);
}
public boolean isSymmetric(TreeNode root) {
return isEquivalent(root.left, root.right);
}
}