前言:
二叉树的题目绝大多数都可以利用递归来解决,熟练掌握二叉树的前中后序遍历以及层序遍历是能快速解决二叉树题目的基础。
目录
二叉树的最大深度
思路:
代码:
//给定一颗二叉树返回二叉树的最大深度
class TreeNode{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val){
this.val=val;
}
}
//递归函数
//递归含义:以node为头的这棵树的最大深度
public int process(TreeNode node) {
//base case
if (node == null) {
return 0;
}
return Math.max(process(node.left), process(node.right)) + 1;
}
public int getMaxDepth(TreeNode root){
return process(root);
}
相同的树
思路:
代码:
通过上述思路我们可以轻易的写出代码
public class TreeNode{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val){
this.val=val;
}
}
public boolean isSame(TreeNode root1,TreeNode root2) {
//有三种可能
//1:root1==null&&root2==null
//2:root1和root2有一个节点为null
//3:root1和root2均不为空
if(root1==null^root2==null){
return false;
}
if(root1==null&&root2==null){
return true;
}
return root1.val== root2.val&&isSame(root1.left,root2.left)&&
isSame(root1.right,root2.right);
}
对称二叉树
思路:
代码:
//利用判断两颗二叉树是否相等的思路一样
//左边的左孩子等于右边的右孩子
//左边的右孩子等于右边的左孩子
public boolean isSymmetric(TreeNode node1,TreeNode node2){
if((node1==null)^(node2==null)){
return false;
}
if(node1==null&&node2==null){
return true;
}
return node1.val==node2.val&&isSymmetric(node1.left,node2.right)&&
isSymmetric(node1.right,node2.left);
}
public boolean isSymmetric(TreeNode root) {
return isSymmetric(root,root);
}
判断平衡二叉树
思路:
通过整合上述思路我们可以快速的写出代码。
代码:
public class Info{
public boolean isBalanced;
public int height;
public Info(boolean a,int b){
isBalanced=a;
height=b;
}
}
public Info process(TreeNode node){
if(node==null){
return new Info(true,0);
}
//向左右子树要信息
Info leftInfo=process(node.left);
Info rightInfo=process(node.right);
//整合出自身的信息
int height=Math.max(leftInfo.height,rightInfo.height)+1;
boolean isBalanced=false;
if(leftInfo.isBalanced&&rightInfo.isBalanced&&
(Math.abs(leftInfo.height-rightInfo.height)<2)){
isBalanced=true;
}
return new Info(isBalanced,height);
}
public boolean isBalanced(TreeNode root) {
return process(root).isBalanced;
}
利用前序遍历与中序遍历生成二叉树
分析:
代码:
//递归函数
//利用preorder的[L.....R]和inorder[L....R]范围内建立出整颗二叉树
//返回整颗二叉树的头节点
//加速优化:没必要每次都遍历查找find
public TreeNode process(int[] preorder, int l, int r, int[] inorder, int L, int R,
HashMap<Integer,Integer> map){
//base case
if(l>r){
return null;
}
TreeNode head=new TreeNode(preorder[l]);
if(l==r){
return head;
}
int find=map.get(preorder[l]);
head.left=process(preorder,l+1,l+find-L,inorder,L,find-1,map);
head.right=process(preorder,r-(R-find)+1,r,inorder,find+1,R,map);
return head;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder==null||inorder==null||preorder.length!=inorder.length){
return null;
}
int N=preorder.length;
//准备一个哈希表,记录中序遍历数组中每一个数值所对应的下标
HashMap<Integer,Integer> valueIndexMap=new HashMap<>();
for(int i=0;i<N;i++){
valueIndexMap.put(inorder[i],i);
}
return process(preorder,0,N-1,inorder,0,N-1,valueIndexMap);
}
由于本人水平十分有限,若有错误请即使告知!如果有帮助别忘了,万分感谢。
点赞👍 收藏✨ 关注✌