LintCode - 二叉树的路径和(普通)

版权声明:本文为博主原创文章,未经博主允许不得转载。

难度:普通
要求:

给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值 的路径。
一个有效的路径,指的是从根节点到叶节点的路径。

样例:

给定一个二叉树,和 目标值 = 5:

     1
    / \
   2   4
  / \
 2   3

返回:

[
  [1, 2, 2],
  [1, 4]
]
思路:

递归遍历

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root the root of binary tree
     * @param target an integer
     * @return all valid paths
     */
    public List> binaryTreePathSum(TreeNode root, int target) {
        List> result = new ArrayList>();

        //获取所有路径
        List list = new ArrayList();
        if(root != null){
            addPath(root,String.valueOf(root.val), list);
        }

        //检查
        for(String path : list){
            String[] paths = path.split(",");
            
            int num = 0;
            for(String val : paths){
                num += Integer.parseInt(val);
            }

            if(target == num){
                List data = new ArrayList();
                for(String val : paths ){
                    data.add(Integer.parseInt(val));
                }
                result.add(data);
            }
        }
        return result;
    }
    
    /**
     * 添加路径 
     */
    private void addPath(TreeNode node,String path,List list){
       if(node == null){
            return;
        }
        
        if(node.left == null && node.right == null){
            list.add(path);
        }
        
        if(node.left != null){
            addPath(node.left,path + "," + String.valueOf(node.left.val),list);
        }
        
        if(node.right != null){
            addPath(node.right,path + "," + String.valueOf(node.right.val),list);
        }
    }
}

你可能感兴趣的:(LintCode - 二叉树的路径和(普通))