LeetCode404---Sum of Left Leaves
Question:
Find the sum of all left leaves in a given binary tree.
Example:
分析:题目很容易理解,求出树的所有左叶子节点的和,需要注意的是,必须是对左叶子节点求和,所以根节点,非叶子节点,右叶子节点都不符合条件
解法一:递归
注意:要弄清楚递归的出口
public static int sumOfLeftLeaves(TreeNode root) { int sum = 0; if (root == null) { return 0; } if (root.left != null) { if (root.left.left == null && root.left.right == null) { sum += root.left.val; } } sum += sumOfLeftLeaves(root.left); sum += sumOfLeftLeaves(root.right); return sum; }
解法二:非递归,使用栈
如果不想采用递归的方法的话,可以考虑使用栈,遍历所有的节点,找出复合条件的节点计算即可。贴上了leetcode上给出的别人写的代码参考一下作为学习
public static int sumOfLeftLeaves(TreeNode1 root) { int sum = 0; Stack<TreeNode1> stack = new Stack<TreeNode1>(); stack.push(root); while(!stack.empty()){ TreeNode1 node1 = stack.pop(); if(node1.left!=null){ if(node1.left.left == null && node1.left.right == null){ sum+=node1.left.val; }else { stack.push(root.left); } } if(node1.right!=null){ if(node1.right.left != null || node1.right.right != null){ stack.push(root.right); } } } return sum; }