首页 > 其他 > 详细

[LeetCode]113 Binary Tree Postorder Traversal

时间:2015-01-02 07:31:09      阅读:284      评论:0      收藏:0      [点我收藏+]

https://oj.leetcode.com/problems/path-sum-ii/

http://fisherlei.blogspot.com/search?q=Path+Sum+II+


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        
        // 需要遍历树
        // 对于每个节点,记录从root到此节点(包含)的路径值和路径,可以用map来储存
        // 当遇到leaf,且符合条件,加入到result
        
        List<List<Integer>> result = new ArrayList<>();
        if (root == null)
            return result;
            
        Map<TreeNode, Path> pathmap = new HashMap<>();
        pathmap.put(root, Path.append(new Path(), root));
        
        find(root, sum, pathmap, result);
        
        return result;
    }
    
    private void find(TreeNode node, int target, Map<TreeNode, Path> pathmap, List<List<Integer>> result)
    {
        Path path = pathmap.get(node);
        
        if (node.left == null && node.right == null)
        {
            // A leaf
            if (path.sum == target)
            {
                result.add(path.path);
            }
            return;
        }
        
        if (node.left != null)
        {
            Path leftpath = Path.append(path, node.left);
            pathmap.put(node.left, leftpath);
            find(node.left, target, pathmap, result);
        }
        
        if (node.right != null)
        {
            Path rightpath = Path.append(path, node.right);
            pathmap.put(node.right, rightpath);
            find(node.right, target, pathmap, result);
        }
    }
    
    private static class Path
    {
        int sum;
        List<Integer> path;
        
        Path()
        {
            sum = 0;
            path = new ArrayList();
        }
        
        static Path append(Path p, TreeNode node)
        {
            Path toReturn = new Path();
            toReturn.sum = p.sum + node.val;
            toReturn.path = new ArrayList<Integer>(p.path);
            toReturn.path.add(node.val);
            return toReturn;
        }
    }
}


[LeetCode]113 Binary Tree Postorder Traversal

原文:http://7371901.blog.51cto.com/7361901/1598373

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!