文章目录
- 前言
- Leetcode 102 二叉树的层序遍历
- 题目讲解
- Leetcode 226.翻转二叉树
- 题目讲解
- Leetcode 101. 对称二叉树
- 题目讲解
- 递归法
- 总结
前言
递归三定律
- 确定参数和返回值
- 确认终止条件
- 确认单层递归的逻辑
Leetcode 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>> reslist = new ArrayList< List< Integer>> ();
public List<List<Integer>> levelOrder(TreeNode root) {
check02(root);
return reslist;
}
public void check02(TreeNode node)
{
Queue <TreeNode> que =new LinkedList<TreeNode>();
if( node == null)
{
return;
}
que.offer(node);
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--; //次数减一
}
//在统一放到二维数组里
reslist.add( ItemList);
}
}
}
Leetcode 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;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if( root ==null)
{
return null;
}
//左
invertTree( root.left);
// 右
invertTree(root.right);
//中
swapChildern(root);
return root;
}
public void swapChildern(TreeNode root)
{
TreeNode tempnode = root.left;
root.left =root.right;
root.right =tempnode;
}
}
Leetcode 101. 对称二叉树
(优先掌握递归)
题目讲解
递归法
递归三部曲
- 1 确认递归函数的参数和返回值
参数是左子树节点 和右子树节点因为要判断两个节点是否翻转来判断这个树对称不
返回类型为bool
2 确认终止条件
如果左右节点都不为空,比较节点数值,不相同就return false;
这道题只能使用后序遍历,左右孩子分别处理完之后 才能返回给根节点,下面是AC代码
AC代码
/**
* 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 boolean isSymmetric(TreeNode root) {
return compare(root.left,root.right);
}
public 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 compareOutSide = compare(left.left,right.right);
boolean compareInSide = compare(left.right,right.left);
return compareInSide&& compareOutSide;
}
}
总结
翻转二叉树的整体思路可以看图
自己做的图加深一下理解
困死了准备休息