226.翻转二叉树
力扣题目链接:. - 力扣(LeetCode)
DFS(前序递归)
在前序遍历的基础上,实现交换即可
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null){
return null;
}
swapNode(root);
invertTree(root.left);
invertTree(root.right);
return root;
}
public void swapNode(TreeNode root){
TreeNode temp=root.left;
root.left=root.right;
root.right=temp;
}
}
BFS
层序遍历
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null){
return null;
}
Deque<TreeNode> myqueue=new LinkedList<>();
myqueue.offer(root);
while(!myqueue.isEmpty()){
int len=myqueue.size();
while(len>0){
TreeNode cur=myqueue.poll();
swap(cur);
if(cur.left!=null){
myqueue.push(cur.left);
}
if(cur.right!=null){
myqueue.push(cur.right);
}
len--;
}
}
return root;
}
public void swap(TreeNode tn){
TreeNode temp=tn.left;
tn.left=tn.right;
tn.right=temp;
}
}
101. 对称二叉树
力扣题目链接:. - 力扣(LeetCode)
DFS(后序递归)
class Solution {
public boolean isSymmetric(TreeNode root) {
return ifsame(root.left,root.right);
}
public boolean ifsame(TreeNode left,TreeNode right){
if(left==null&&right!=null){
return false;
}
else if(right==null&&left!=null){
return false;
}
else if(right==null&&left==null){
return true;
}
else if(right.val!=left.val){
return false;
}else{
boolean out=ifsame(left.left,right.right);
boolean in=ifsame(left.right,right.left);
return out&∈
}
}
}
104.二叉树的最大深度
BFS
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
Deque<TreeNode> myqueue=new LinkedList<>();
myqueue.offer(root);
int depth=0;
while(!myqueue.isEmpty()){
depth++;
int len=myqueue.size();
while(len>0){
TreeNode cur=myqueue.poll();
if(cur.right!=null){
myqueue.offer(cur.right);
}
if(cur.left!=null){
myqueue.offer(cur.left);
}
len--;
}
}
return depth;
}
}
111.二叉树的最小深度
BFS
class Solution {
public int minDepth(TreeNode root) {
if(root==null){
return 0;
}
Deque<TreeNode> myqueue=new LinkedList<>();
myqueue.offer(root);
int minDepth=0;
while(!myqueue.isEmpty()){
int len=myqueue.size();
minDepth++;
while(len>0){
TreeNode cur=myqueue.poll();
boolean existleft=false;
boolean existright=false;
if(cur.left!=null){
myqueue.offer(cur.left);
existleft=true;
}
if(cur.right!=null){
myqueue.offer(cur.right);
existright=true;
}
if(!(existleft||existright))
return minDepth;
len--;
}
}
return minDepth;
}
}