一、LeetCode 102 二叉树的层序遍历
题目链接:
102.二叉树的层序遍历https://leetcode.cn/problems/binary-tree-level-order-traversal/
思路:利用队列的先进先出特性,在处理本层节点的同时将下层节点入队,每次处理一层的节点,即可实现层序遍历。
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
List<List<Integer>> ans = new ArrayList<>();
if(root == null){
return ans;
}
queue.offer(root);
while(!queue.isEmpty()){
//本层节点数
int size = queue.size();
List<Integer> list = new ArrayList<>();
//记录本层节点 并将下层节点入队
for(int i = 0; i < size; i++){
TreeNode temp = queue.poll();
list.add(temp.val);
if(temp.left != null){
queue.offer(temp.left);
}
if(temp.right != null){
queue.offer(temp.right);
}
}
ans.add(new ArrayList(list));
}
return ans;
}
}
/**
* 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;
* }
* }
*/
二、LeetCode 226 翻转二叉树
题目链接:
226.翻转二叉树https://leetcode.cn/problems/invert-binary-tree/
思路:利用二叉树递归实现前序遍历的思想,在访问每个节点时进行交换其左右子树的操作
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null){
return root;
}
//翻转左右子树 中
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
//前序递归遍历 左、右
invertTree(root.left);
invertTree(root.right);
return root;
}
}
/**
* 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;
* }
* }
*/
三、LeetCode 101 对称二叉树
题目链接:
101.对称二叉树https://leetcode.cn/problems/symmetric-tree/
思路:利用后序遍历思想,分别判断外层和里层节点的轴对称情况(左子树左右中、右子树右左中),并对各种空节点情况进行处理,从而判断整棵树的对称情况。
class Solution {
public boolean isSymmetric(TreeNode root) {
return judge(root.left,root.right);
}
public boolean judge(TreeNode left, TreeNode right){
//处理空节点及镜像节点值不相等的情况
if(left == null && right == null){
return true;
}else if(left == null && right != null){
return false;
}else if(left != null && right == null){
return false;
}else if(left.val != right.val){
return false;
}
//分别判断外层和里层的对称情况
boolean out_flag = judge(left.left, right.right);
boolean in_flag = judge(left.right, right.left);
//只能采用后序遍历,因为需要先判断外层和里层的轴对称情况
return out_flag && in_flag;
}
}
/**
* 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;
* }
* }
*/
四、今日小结
今天的二叉树题目只掌握了递归解法,层序遍历相关题目还未刷,需要找时间补上ovo