算法跟学Day17【代码随想录】

大纲

第六章 二叉树part04

大纲

● 110.平衡二叉树
● 257. 二叉树的所有路径
● 404.左叶子之和

leetcode 110 平衡二叉树

思路

细节

代码

class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) return true;
        if (Math.abs(getDepth(root.left) - getDepth(root.right)) > 1) return false;
        return isBalanced(root.left) && isBalanced(root.right);
    }

    public int getDepth(TreeNode node) {
        if (node == null) return 0;
        return 1 + Math.max(getDepth(node.left), getDepth(node.right)); 
    }
}

复杂度

  • 时间 O(n)
  • 空间 O(n)

leetcode 257 二叉树的所有路径

思路

细节

代码

class Solution {

    List<Integer> paths = new ArrayList<>();
    List<String> res = new ArrayList<>();
    public List<String> binaryTreePaths(TreeNode root) {
        if (root == null) return res;        
        dfs(root);
        return res;
    }

    public void dfs(TreeNode node) {
        paths.add(node.val);
        if (node.left == null && node.right == null) {
            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 (node.left != null) {
            dfs(node.left);
            paths.remove(paths.size() - 1);
        }
        if (node.right != null) {
            dfs(node.right);
            paths.remove(paths.size() - 1);
        }
    }
}

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if (root == null) return res;
        Stack<Object> stack = new Stack<>();
        stack.push(root);
        stack.push(root.val + "");
        while (!stack.isEmpty()) {
            String path = (String) stack.pop();
            TreeNode node = (TreeNode) stack.pop();
            if (node.left == null && node.right == null) res.add(path);
            if (node.right != null) {
                stack.push(node.right);
                stack.push(path + "->" + node.right.val);
            }
            if (node.left != null) {
                stack.push(node.left);
                stack.push(path + "->" + node.left.val);
            }
        }
        return res;
    }
}

复杂度

  • 时间 O(n)
  • 空间 O(n)

leetcode 404 左叶子之和

思路

  • 你华1A秒了

细节

代码

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

复杂度

  • 时间 O(n)
  • 空间 O(n)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值