第十七天|110.平衡二叉树,257. 二叉树的所有路径
110_关键字:二叉树,递归
110_题目链接
代码实现
package LeetCode;
public class YangSibo_110 {
}
class YangSibo_110_1 {
public boolean isBalanced(TreeNode root) {
if(getHight(root)==-1) return false;
return true;
}
public int getHight(TreeNode root) {
if (root == null) return 0;
int left = getHight(root.left);
int right = getHight(root.right);
if(left == -1 || right == -1) return -1;
if((Math.abs(left - right)) > 1){
return -1;
}else {
return ((left > right)? left:right)+1;
}
}
}
解题注意事项
1、了解平衡二叉树的概念
2、递归三要素 入参和出参确认 递归结束条件,单次递归处理顺序
257_关键字:二叉树,递归,回溯
257_题目链接
代码实现
package LeetCode;
import java.util.ArrayList;
import java.util.List;
public class YangSibo_257 {
}
class YangSibo_257_1 {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
List<Integer> pathnode = new ArrayList<>();
if(root == null) return null;
getPath(root,result,pathnode);
return result;
}
public void getPath (TreeNode cur,List<String> result,List<Integer> pathnode) {
pathnode.add(cur.val);
if(cur.left == null && cur.right == null) {
String s = "";
for(int i=0;i<pathnode.size() -1;i++){
s = s + pathnode.get(i);
s = s + "->";
}
s = s + pathnode.get(pathnode.size()-1);
result.add(s);
return;
}
if(cur.left != null){
getPath(cur.left,result,pathnode);
pathnode.remove(pathnode.size()-1);
}
if(cur.right != null){
getPath(cur.right,result,pathnode);
pathnode.remove(pathnode.size()-1);
}
}
}
解题注意事项
1、回溯也意味着遍历结束,把这个点处理结束,后续遍历
2、找到叶子节点再开始构造路径