题目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;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
/*//平衡二叉树->高度->root节点的左节点和右节点是否是高度差<=1->后序遍历->迭代法
//1.输入参数,和输出
public int getHeight(ListNode cur){
int d;
return -1;
return d;
}
//2.终止条件
if(cur==null){
break
}
//3.单层逻辑
//1.左/右节点本身就是不平衡二叉树
if( getHeight(cur.left())==-1||getHeight(cur.right())==-1){
return -1;
}
//左右相剪
int d;
d=|getHeight(cur.left())-getHeight(cur.right())|
if(d<=1){
return d;
}else{
return -1;
}*/
return getHeight(root)!=-1;
//主方法
}
public int getHeight(TreeNode cur){
if(cur==null){
return 0;
}
if( getHeight(cur.left)==-1||getHeight(cur.right)==-1){
return -1;
}
int d;
d=Math.abs(getHeight(cur.left)-getHeight(cur.right));
if(d<=1){
return Math.max(getHeight(cur.left),getHeight(cur.right))+1;
}else{
return -1;
}
}
}
题目二:二叉树的所有路径
给你一个二叉树的根节点 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;
* }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
//1.主方法
List<String> res=new ArrayList<>();
if(root==null){
return res;
}
List<Integer> paths=new ArrayList<>();
traveral(root,paths,res);
return res;
}
private void traveral(TreeNode root, List<Integer>paths,List<String>res){
//1.前序遍历添加中
paths.add(root.val);
//遇到叶子节点
if(root.left==null&&root.right==null){
//遍历输出path里的各个节点的值
StringBuilder sb=new StringBuilder();
for(int i=0;i<paths.size()-1;i++){
sb.append(paths.get(i)).append("->");
}
sb.append(paths.get(paths.size()-1));
res.add(sb.toString());//收集一个路径
return ;
}
if(root.left!=null){
traveral(root.left,paths,res);
paths.remove(paths.size()-1);//回溯
}
if(root.right!=null){
traveral(root.right,paths,res);
paths.remove(paths.size()-1);//回溯
}
}
}