程式碼隨想錄演算法訓練營第十七天| 110. 平衡二叉樹 257. 二叉樹的所有路徑 404. 左葉子之和

jeasonGo發表於2024-03-22

110. 平衡二叉樹
https://leetcode.cn/problems/balanced-binary-tree/description/

public boolean isBalanced(TreeNode root) {
        int balance = balance(root);
        return balance == -1 ? false : true;
    }
    public int balance(TreeNode node){
        if (node == null) return 0;
        int left = balance(node.left);
        if (left == -1) return -1;
        int right = balance(node.right);
        if (right == -1) return -1;
        return Math.abs(left - right) > 1 ? - 1 : Math.max(left,right) + 1;
    }

總結:需要用到左右孩子的高度去比對,所以後序,左右孩子有一個不是平衡的,就不用比了,要不就比左右孩子的差的絕對值,每次如果不是平衡,返回-1,是平衡,返回當前節點的高度。
257. 二叉樹的所有路徑
https://leetcode.cn/problems/binary-tree-paths/description/

public List<String> binaryTreePaths(TreeNode root) {
        List<String> list = new ArrayList<>();
        String s = String.valueOf(root.val);
        preorder(root,list,s);
        return list;
    }
    public void preorder(TreeNode node,List<String> list,String s){
        if (node.left == null && node.right == null){
            list.add(s);
            return;
        }
        if (node.left != null){
            StringBuilder stringBuilder = new StringBuilder(s);
            String leftPath = stringBuilder.append("->").append(node.left.val).toString();
            preorder(node.left,list,leftPath);
        }
        if (node.right != null){
            StringBuilder stringBuilder = new StringBuilder(s);
            String rightPath = stringBuilder.append("->").append(node.right.val).toString();
            preorder(node.right,list,rightPath);
        }
    }

總結:前序,慢慢來很輕鬆
404. 左葉子之和
https://leetcode.cn/problems/sum-of-left-leaves/description/

public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) return 0;
        int leftValue = 0;
        if (root.left != null && root.left.left == null && root.left.right == null){
            leftValue = root.left.val;
        }
        return leftValue + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
    }

相關文章