码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]113 Binary Tree Postorder Traversal

时间:2015-01-02 07:33:25      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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

标签:leetcode

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!