【问题标题】:Find ALL the paths in a binary tree equal to a sum在二叉树中找到所有等于和的路径
【发布时间】:2017-07-31 21:55:27
【问题描述】:

例如,给定以下二叉树:

[2,3,5,4,8,6,-2,null,null,null,null,null,null,null,2] 和 sum = 7

                        2
                      /     \
                    3         5
                 /     \    /   \
                4       8  6     -2
                                  \
                                   2

打印:[3,4] , [2,5] , [2,5,-2,2]

我可以想出一个 n^2 的解决方案,但有更好的解决方案吗?也许有一些额外的内存,比如使用堆栈或哈希表。

我花了 4 个小时试图提出一些解决方案,但所有解决方案都变得太丑陋或混乱。

我的 n^2 解决方案比较简单: 1)有一种方法,即递归调用自身直到所有叶子的助手。当它找到带有总和的路径时,将其添加到结果中。 (这将花费 O(n)) 2)为树中的每个节点调用此方法( O(n) * O(n) = O(n^2))

我的简单解决方案

//TreeNode structure
public class TreeNode {
     int val;
     public TreeNode left;
     public TreeNode right;
    TreeNode(int x) { val = x; }
     }

//Solution class
public class Solution {

    public List<List<Integer>> pathSum(TreeNode root, int sum) {

        List<Integer> temp = new ArrayList<Integer>();
        List<List<Integer>> result = new ArrayList<>();

        if (root == null) return result;
        Queue<TreeNode> q = new LinkedList<>();

        q.offer(root);


        while ( !q.isEmpty())
        {
            TreeNode top = q.poll();
            helper(top,sum,temp,result);

            if (top.left != null) q.offer(top.left);
            if (top.right != null) q.offer(top.right);
        }


        return result;
    }

    public void helper(TreeNode root, int sum, List<Integer> temp, List<List<Integer>> result)
    {


    if (root == null) return;
    temp.add(root.val) ;
    if (root.val == sum) 
    {

        result.add(new ArrayList<>(temp));
    }

    helper(root.left,sum-root.val, temp, result );
    helper(root.right, sum-root.val, temp, result);

    temp.remove(temp.size() - 1);

    }

    }

//Execution class
public class treeApp {

public static void main(String args[])
{    TreeNode root = new TreeNode(2);
    root.left = new TreeNode(3);
    root.right = new TreeNode(5);

    root.left.left = new TreeNode(4);
    root.left.right = new TreeNode(8);

    root.right.left = new TreeNode(6);
    root.right.right = new TreeNode(-2);

    root.right.right.right = new TreeNode(2);

    Solution sol = new Solution();

    List<List<Integer>> result ;
    result = sol.pathSum(root, 7);

    for (List l : result)
    {
        System.out.println(l.toString());
    }

}
//Prints:
[2, 5]
[2, 5, -2, 2]
[3, 4]

【问题讨论】:

    标签: algorithm recursion optimization time-complexity binary-tree


    【解决方案1】:

    以任何方便的方式(广度优先或深度优先)遍历树,但包括该节点的路径。

    在每个节点,检查所有在该节点结束的路径和;如果有任何等于目标值,则将这些路径添加到解决方案(作为函数结果传回)。

    然后递归:将当前节点添加到路径并调用每个子节点。

    这足够清楚了吗?我认为这可以在更短的时间内解决问题。遍历是 O(N) 到达所有节点。在每个节点上,您都会穿过长度为 的路径。如果你有一个平衡二叉树,深度是 O(log2[N])。

    【讨论】:

      猜你喜欢
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多