• 力扣404题(左叶子之和)


    404、左叶子之和

    具体实现:

    1、递归参数和返回值

    参数:根节点

    返回值:数值之和

    2、终止条件

    root==null

    3、单层递归的逻辑

    遇到左叶子节点的时候,记录数值

    通过递归求左子树左叶子之和

    右子树左叶子之和

    相加就是整个树的左叶子之和

    代码:

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

    迭代

    class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if (root == null) return 0;
            Stack<TreeNode> stack = new Stack<> ();
            stack.add(root);
            int result = 0;
            while (!stack.isEmpty()){
                TreeNode node = stack.pop();
                if (node.left != null && node.left.left == null && node.left.right == null) {
                    result += node.left.val;
                }
                if (node.right != null) stack.add(node.right);
                if (node.left != null) stack.add(node.left);
            }
            
            return result;
        }
    }
  • 相关阅读:
    ES6中对象新增方法
    ES6中字符串新增方法
    Laya 吐槽日志.
    汇编与反汇编工具
    Mac 软件下载地址
    红米手机 android4.4.4 root之路
    查看apk安装包信息
    文件搜索
    自动发表QQ空间说说
    批量格式化json
  • 原文地址:https://www.cnblogs.com/zhaojiayu/p/15536191.html
Copyright © 2020-2023  润新知