102.二叉树的层序遍历
- 刷题https://leetcode.cn/problems/binary-tree-level-order-traversal/description/
- 文章讲解https://programmercarl.com/0102.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%B1%82%E5%BA%8F%E9%81%8D%E5%8E%86.html
- 视频讲解https://www.bilibili.com/video/BV1GY4y1u7b2/?vd_source=af4853e80f89e28094a5fe1e220d9062
-
题解1(迭代法):
/*** 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>> resultList = new ArrayList<List<Integer>>();//主函数public List<List<Integer>> levelOrder(TreeNode root) {checkFun(root);return resultList;}//借助队列public void checkFun(TreeNode cur){//若为空,则直接返回if(cur == null){return;}//创建链辅助队列,并加入根结点Queue<TreeNode> que = new LinkedList<TreeNode>();que.offer(cur);//当辅助队列内非空while(!que.isEmpty()){List<Integer> itemList = new ArrayList<Integer>();int len = que.size();while(len > 0){TreeNode tempNode = que.poll();itemList.add(tempNode.val);if(tempNode.left != null){que.offer(tempNode.left);}if(tempNode.right != null){que.offer(tempNode.right);}len--;}resultList.add(itemList);}}
}
/*** 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>> resultList = new ArrayList<List<Integer>>();//递归遍历public void checkFun(TreeNode cur, Integer deep){//若传入二叉树为空,则直接返回if(cur == null){return;}//传入二叉树非空,则先遍历深度+1deep++;//当前遍历结果中层数小于当前deep,则进行遍历if(resultList.size() < deep){//层级增加时,list的Item增加,利用list索引值进行层级界定List<Integer> item = new ArrayList<Integer>();resultList.add(item);}//将当前遍历结点加入结果数组resultList.get(deep - 1).add(cur.val);checkFun(cur.left, deep);checkFun(cur.right,deep);}//主函数public List<List<Integer>> levelOrder(TreeNode root) {checkFun(root, 0);return resultList;}
}
226.翻转二叉树
- 刷题https://leetcode.cn/problems/invert-binary-tree/description/
- 文章讲解https://programmercarl.com/0226.%E7%BF%BB%E8%BD%AC%E4%BA%8C%E5%8F%89%E6%A0%91.html
- 视频讲解https://www.bilibili.com/video/BV1sP4y1f7q7/?vd_source=af4853e80f89e28094a5fe1e220d9062
-
题解(后序递归法):
/*** 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;}invertTree(root.left);invertTree(root.right);swapChildren(root);return root;}private void swapChildren(TreeNode root){TreeNode temp = root.left;root.left = root.right;root.right = temp;}
}