第十七天|110.平衡二叉树,257. 二叉树的所有路径

第十七天|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、找到叶子节点再开始构造路径

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值