404. Sum of Left Leaves

本文介绍了一种算法问题——求给定二叉树中所有左叶子节点的和,并提供了四种不同的解决方案,包括DFS迭代、DFS递归、先序遍历加标记以及队列BFS方法。

题目描述:

Find the sum of all left leaves in a given binary tree.

class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }

思路一:

DFS迭代,利用Stack

对于一个给定的结点,判断它的左孩子是不是叶子结点,如果是,将它的值加到返回值上去,如果不是,加入stack。

判断它的右孩子是不是叶子结点,如果不是,加入stack。

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) return 0;
        int res = 0;
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        while (!stack.isEmpty())
        {
            TreeNode node = stack.pop();
            if (node.left != null)
            {
                if (node.left.left == null && node.left.right == null)
                    res += node.left.val;
                else
                    stack.push(node.left);
            }
            if (node.right != null)
            {
                if (node.right.left != null || node.right.right != null)
                    stack.push(node.right);
            }
        }
        return res;
    }
}

思路二:DFS递归

对于一个给定的结点,判断其左孩子是不是叶子结点,如果是叶子结点,将值加到返回值上去,如果不是,递归调用。

递归调用其右孩子。

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) return 0;
        int res = 0;
        if (root.left != null)
        {
            if (root.left.left == null && root.left.right == null)
                res += root.left.val;
            else
                res += sumOfLeftLeaves(root.left);
        }
        res += sumOfLeftLeaves(root.right);
        return res;
    }
}
思路三:先序遍历,加flag判断是否为左孩子

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) return 0;
        return preorder(root, false);
    }
    public int preorder(TreeNode root, boolean left)
    {
        if (root == null)
            return 0;
        if (root.left == null && root.right == null && left)
            return root.val;
        return preorder(root.left, true) + preorder(root.right, false);
    }
}

思路四:队列BFS

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) return 0;
        int res = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty())
        {
            TreeNode node = queue.poll();
            if (node.left != null && node.left.left == null && node.left.right == null)
                res += node.left.val;
            if (node.left != null)
                queue.add(node.left);
            if (node.right != null)
                queue.add(node.right);
        }
        return res;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值