一、 102.二叉树的层序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null){
return res;
}
Queue<TreeNode> que = new LinkedList<>();
que.offer(root);
while(!que.isEmpty()){
List<Integer> lineRes = new ArrayList<>();
int len = que.size();
while(len > 0){
TreeNode treeNode = que.poll();
lineRes.add(treeNode.val);
if(treeNode.left != null){
que.offer(treeNode.left);
}
if(treeNode.right != null){
que.offer(treeNode.right);
}
len--;
}
res.add(lineRes);
}
return res;
}
}
二、 226.翻转二叉树
public static TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
if (root.left != null) {
invertTree(root.left);
}
if (root.right != null) {
invertTree(root.right);
}
TreeNode tmpNode = root.left;
root.left = root.right;
root.right = tmpNode;
return root;
}
三、 101. 对称二叉树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null){
return null;
}
if (root.left != null) {
invertTree(root.left);
}
if (root.right != null) {
invertTree(root.right);
}
TreeNode tmpNode = root.left;
root.left = root.right;
root.right = tmpNode;
return root;
}
}