美文网首页leetcode
LeetCode:404. 左叶子之和

LeetCode:404. 左叶子之和

作者: xlesterx | 来源:发表于2018-11-16 09:50 被阅读15次

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

示例:

    3
   / \
  9  20
    /  \
   15   7

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

方法一:

思想:把所有节点都当作根节点。递归处理

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
       public int sumOfLeftLeaves(TreeNode root) {
      if (root == null) {
            return 0;
        }
        Stack<TreeNode> rightStack = new Stack<>();
        int sum = 0;
        do {
            TreeNode left = root.left;
            TreeNode right = root.right;
            if (right != null) {
                rightStack.add(right);
            }
            if (left != null) {
                sum += getLeftValue(left, rightStack);
            }
            root = rightStack.empty() ? null : rightStack.pop();
        } while (root != null);
        return sum;
    }

 private  int getLeftValue(TreeNode root, Stack<TreeNode> rightStack) {
    if (root.right != null) {
      rightStack.add(root.right);
    }
    if (root.left != null) {
      return getLeftValue(root.left, rightStack);
    }

    return root.right == null ? root.val : 0;
  }

方法二

参考更简单的递归方法

  public static int sumOfLeftLeaves(TreeNode root) {
    if (root == null) return 0;
    return getValue(root.left, true) + getValue(root.right, false);

  }

  private static int getValue(TreeNode node, boolean isLeft) {
    if (node == null) return 0;
    // 叶子节点
    if (node.left == null && node.right == null) return isLeft ? node.val : 0;

    return getValue(node.left, true) + getValue(node.right, false);

  }

相关文章

  • LeetCode:404. 左叶子之和

    计算给定二叉树的所有左叶子之和。 示例: 方法一: 思想:把所有节点都当作根节点。递归处理 方法二 参考更简单的递归方法

  • 404. 左叶子之和

    计算给定二叉树的所有左叶子之和。 解:1代表左节点,0代表右节点

  • 404. 左叶子之和

    计算给定二叉树的所有左叶子之和。 示例: / 9 20/ 15 7 在这个二叉树中,有两个左叶子,分别是 ...

  • 【LeetCode】左叶子之和

    题目描述: https://leetcode-cn.com/problems/sum-of-left-leaves...

  • 左叶子之和

    左叶子之和 https://leetcode-cn.com/problems/sum-of-left-leaves...

  • 左叶子之和

    左叶子之和,给定二叉树的根节点 root ,返回所有左叶子之和。 输入: root = [3,9,20,null,...

  • 2021-12-16 404. 左叶子之和【Easy】

    计算给定二叉树的所有左叶子之和。 示例: 方法一:

  • 404-左叶子之和

    左叶子之和 题目 计算给定二叉树的所有左叶子之和。 示例: 在这个二叉树中,有两个左叶子,分别是 9 和 15,所...

  • 2019-03-27 待提高

    1.#### 左叶子之和 计算给定二叉树的所有左叶子之和。 示例: / 9 20/ 15 7 在这个二叉树...

  • Hot100 LeetCode(三)

    1. 求根到叶子节点数字之和(dfs、bfs) 求根到叶子节点数字之和(leetcode有2道相同的该题) :ht...

网友评论

    本文标题:LeetCode:404. 左叶子之和

    本文链接:https://www.haomeiwen.com/subject/xeypfqtx.html