226.翻转二叉树
算法链接:
类型: 二叉树
难度: 简单
思路:这道算法题需要注意二叉树的遍历顺序,中左右或者左右中,否则同一段数结构会被先后经过两次更换处理。
题解:
/**
* 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;
* }
* }
*/
//解法1:
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null){
return root;
}
swap(root);
invertTree(root.left);
invertTree(root.right);
return root;
}
void swap(TreeNode root){
TreeNode tmp = new TreeNode();
tmp = root.left;
root.left = root.right;
root.right = tmp;
}
}
//解法2:BFS
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;
* }
* }
*/
//解法1:递归法
class Solution {
public boolean isSymmetric(TreeNode root) {
return compare(root.left,root.right);
}
boolean compare(TreeNode left,TreeNode right){
if(left==null && right!=null){
return false;
}
if(left!=null && right==null){
return false;
}
if(left == null && right ==null){
return true;
}
if(left.val!=right.val){
return false;
}
boolean compareOut = compare(left.left,right.right);
boolean compareIn = compare(left.right,right.left);
return compareIn && compareOut;
}
}
//解法2:双端队列法
//解法3:普通单队列法
104.二叉树的最大深度
算法链接:
104. 二叉树的最大深度 - 力扣(LeetCode)
类型: 二叉树
难度: 简单
思路:二叉树的遍历规律——左右中,左右分别向下递归,结果返回给双方父节点。或者层序遍历记录并且返回二叉树层数的最大值。
题解:
/**
* 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;
* }
* }
*/
//解法1:递归法
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
int l = maxDepth(root.left);
int r = maxDepth(root.right);
return Math.max(l,r)+1;
}
}
//解法2:迭代法(层序遍历)
111.二叉树的最小深度
算法链接:
111. 二叉树的最小深度 - 力扣(LeetCode)
类型: 二叉树
难度: 简单
思路:与二叉树的最大深度不同的是,此题需要判断终结点是否为叶子节点(左右孩子节点为null),是则返回,否则记录+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;
* }
* }
*/
//解法1:递归法
class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
int l = minDepth(root.left);
int r = minDepth(root.right);
if(root.left == null){
return r+1;
}
if(root.right == null){
return l+1;
}
return Math.min(l,r)+1;
}
}
//解法2:迭代法(层序遍历找叶子节点)