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; } }