[leetCode]404. 左叶子之和

题目

链接:https://leetcode-cn.com/problems/sum-of-left-leaves

计算给定二叉树的所有左叶子之和。

示例:

    3
   / \
  9  20
    /  \
   15   7

在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24

递归

判断当前节点是不是左叶子是无法判断的,必须要通过节点的父节点来判断其左孩子是不是左叶子。

if (node->left != NULL && node->left->left == NULL && node->left->right == NULL) {
    左叶子节点处理逻辑
}

递归三步走:

  1. 确定函数返回值与函数参数
  2. 确定退出条件
  3. 确定单层逻辑

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) return 0;
        int leftValue = sumOfLeftLeaves(root.left);
        int rightValue = sumOfLeftLeaves(root.right);

        int midValue = 0;
        if (root.left != null && root.left.left == null && root.left.right == null)
            midValue = root.left.val;
        int sum = leftValue + rightValue + midValue;
        return sum;
    }
}

迭代

使用先序或者后序遍历都可以

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) return 0;
        LinkedList<TreeNode> stack = new LinkedList<>();
        stack.push(root);
        int sum = 0;
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (node != null) {
                stack.push(node);
                stack.push(null);
                if (node.right != null)
                    stack.push(node.right);
                if (node.left != null) {
                    stack.push(node.left);
                }
            } else {
                TreeNode cur = stack.pop();
                if (cur.left != null && cur.left.left == null && cur.left.right == null) {
                    sum += cur.left.val;
                }
            }
        }
        return sum;
    }
}
posted @ 2020-11-03 13:07  消灭猕猴桃  阅读(34)  评论(0编辑  收藏  举报