代码随想录 第17天 | ● 110.平衡二叉树 ● 257. 二叉树的所有路径 ● 404.左叶子之和

leetcode:110. 平衡二叉树 - 力扣(LeetCode)

class Solution {
    public boolean isBalanced(TreeNode root) {

        return getblan(root) != -1;

    }

    private int getblan(TreeNode root) {
        //为空退出 后序遍历
        if(root == null) return 0;
        //左节点高度
        int leftheight = getblan(root.left);
        //-1说明不平衡
        if(leftheight == -1) return -1;
        //有节点高度
        int rightheight = getblan(root.right);
        //同上
        if(rightheight == -1) return -1;
        //核心 判断左右高度差值
        if(Math.abs(leftheight - rightheight) > 1) return -1;
        //代码能运行到这,说明是平衡
        return 1 + Math.max(leftheight,rightheight);

    }
}

leetcode:257. 二叉树的所有路径 - 力扣(LeetCode)

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        if(root == null) return result;
        List<Integer> path = new ArrayList<>();
        getpath(root,path,result);
        return  result;
    }

    private void getpath(TreeNode root, List<Integer> path, List<String> result) {
        //前序 中
        path.add(root.val);
        //遇到叶子结点
        if(root.left == null && root.right == null){
            StringBuffer sb = new StringBuffer();
            //添加除了最后一个元素 ->
            for(int i = 0 ;i < path.size() -1 ;i++){
                sb.append(path.get(i)).append("->");
            }
            //合并最后一个元素
            sb.append(path.get(path.size() - 1));
            result.add(sb.toString()) ;
        }
        //
        if( root.left !=null){
            getpath(root.left,path,result);
            //回溯到上一个节点
            path.remove(path.size()-1);
        }
        //
        if( root.right !=null){
            getpath(root.right,path,result);
            //回溯到上一个节点
            path.remove(path.size()-1);
        }
    }
}

leetcode:404. 左叶子之和 - 力扣(LeetCode)

思路:差一点出来,就差在minvalue,我写成return了,return只能记录第一个节点,往后的right左子叶都累加不了。

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if(root == null) return 0;
        //后序
        //左 右 中
        int leftsum = sumOfLeftLeaves(root.left);
        int rightsum = sumOfLeftLeaves(root.right);
        //
        int minvalue = 0;
        //判断左节点是否是左叶子节点,是就将该节点的值记录,之前写的return,不能记录右节点的左叶子节点,没有累加的作用
        if( root.left != null && root.left.left == null && root.left.right == null  ){
            minvalue = root.left.val;
        }

        int sum =leftsum + rightsum + minvalue;

        return sum;

    }
}

 

posted @ 2024-03-10 14:26  22软工冷薄  阅读(1)  评论(0编辑  收藏  举报