LeetCode Sum of Left Leaves
2017-08-25 23:15
337 查看
Find the sum of all left leaves in a given binary tree.
Example:
题意:计算一棵二叉树所有左叶子节点的节点和。注意:这里是左叶子节点,也就是说是叶子节点,那么就必须是在最底一层,然后是左叶子节点,那么它相对于根节点而言,是在左侧。理解了这两点后,我考虑用层次遍历来实现,并且用hashmap来存储相应的节点,其中key表示的是treenode,也就是相应的节点,而value则表示此节点对应于根节点而言的位置,是在左侧还是在右侧,如果是根节点,我用0来表示;如果是左节点,那么用1表示;如果是右节点,那么用2表示。在层次遍历中,如果是遇到是左叶子节点,那么将其加到一个表示和的变量sum中;其他则考虑加入到表示节点的对列queue中。代码如下:
Example:
3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
题意:计算一棵二叉树所有左叶子节点的节点和。注意:这里是左叶子节点,也就是说是叶子节点,那么就必须是在最底一层,然后是左叶子节点,那么它相对于根节点而言,是在左侧。理解了这两点后,我考虑用层次遍历来实现,并且用hashmap来存储相应的节点,其中key表示的是treenode,也就是相应的节点,而value则表示此节点对应于根节点而言的位置,是在左侧还是在右侧,如果是根节点,我用0来表示;如果是左节点,那么用1表示;如果是右节点,那么用2表示。在层次遍历中,如果是遇到是左叶子节点,那么将其加到一个表示和的变量sum中;其他则考虑加入到表示节点的对列queue中。代码如下:
public class sumOfLeftLeaves { public int sumOfLeftLeaves(TreeNode root) { if(root == null) return 0; Queue<HashMap<TreeNode,Integer>> queue = new LinkedList<>(); HashMap<TreeNode,Integer> hroot = new HashMap<>(); hroot.put(root,0); queue.add(hroot); int length = queue.size(); int sum = 0; while(!queue.isEmpty()) { while(length-- > 0) { HashMap htmp = queue.poll(); Set set = htmp.keySet(); Iterator iter = set.iterator(); while (iter.hasNext()) //这里是用来求得一棵二叉树所对应的key值 { TreeNode treetmp = (TreeNode) iter.next(); int tmp = (Integer) htmp.get(treetmp); if (tmp == 0 || tmp == 2) //判断value的值,如果是0,则表示为根节点,为2表示为右子节点 { if (treetmp.left != null) { HashMap<TreeNode, Integer> hashmaptmp1 = new HashMap<>(); hashmaptmp1.put(treetmp.left, 1); queue.add(hashmaptmp1); } if (treetmp.right != null) { HashMap<TreeNode, Integer> hashmaptmp2 = new HashMap<>(); hashmaptmp2.put(treetmp.right, 2); queue.add(hashmaptmp2); } } else if (tmp == 1) //value为2,则表示为右子节点 { if(treetmp.left == null && treetmp.right == null) //并且需要判断,此右子节点是否为右叶子节点 { sum += treetmp.val; //如果是右叶子节点,则考虑将其加入到求和中 } if (treetmp.left != null) { HashMap<TreeNode, Integer> hashmaptmp3 = new HashMap<>(); hashmaptmp3.put(treetmp.left, 1); queue.add(hashmaptmp3); } if (treetmp.right != null) { HashMap<TreeNode, Integer> hashmaptmp4 = new HashMap<>(); hashmaptmp4.put(treetmp.right, 2); queue.add(hashmaptmp4); } } } length = queue.size(); } } return sum; } }
相关文章推荐
- LeetCode: Sum of Left Leaves
- 【LeetCode】404 Sum of Left Leaves(java实现)
- LeetCode-Sum of Left Leaves
- LeetCode 404 Sum of Left Leaves
- LeetCode 404: Sum of Left Leaves
- 【LeetCode】404 Sum of Left Leaves(java实现)
- leetcode 404 Sum of Left Leaves
- LeetCode-404-Sum of Left Leaves-E
- LeetCode : Sum of Left Leaves
- Leetcode 404 Sum of Left Leaves
- 【LeetCode】Sum of Left Leaves 左叶子之和
- LeetCode@HashMap_404_Sum_of_Left_Leaves
- Leetcode #404 Sum of Left Leaves
- leetcode404: Sum of Left Leaves
- LeetCode Sum of Left Leaves
- [LeetCode] Sum of Left Leaves 左子叶之和
- LeetCode 404 Sum of Left Leaves (DFS)
- Leetcode Sum of Left Leaves
- LEETCODE--Sum of Left Leaves
- LeetCode[404] Sum of Left Leaves