【IT笔试面试题整理】二叉树中和为某一值的路径--所有可能路径

【试题描述】

     You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum up to that value. Note that it can be any path in the tree-it does not have to start at the root.

     输入一个整数和一棵二元树。从树的任意结点开始往下访问所经过的所有结点形成一条路径。

打印出和与输入整数相等的所有路径。

 

解题思路:

 

      一层一层的遍历,保存当前节点到根节点的完整路径,然后从当前节点向上扫描,如果找到了当前节点到某个节点的和等于给定值,则输出之。程序对每个节点都需要遍历一遍,还要扫描当前节点到根节点的路径,且需要保存每个节点到根节点的路径,所以时间复杂度为O(nlgn),空间复杂度为O(nlgn)。

 1 public static void findAllPath(Node head, int sum, ArrayList<Integer> buffer, int level)
 2     {
 3         if (head == null)
 4             return;
 5         int tmp = sum;
 6         buffer.add(head.value);
 7         for (int i = level; i >= 0; i--)
 8         {
 9             tmp -= buffer.get(i);
10             if (tmp == 0)
11                 print(buffer, i, level);
12         }
13 
14         ArrayList<Integer> c1 = (ArrayList<Integer>) buffer.clone();
15         ArrayList<Integer> c2 = (ArrayList<Integer>) buffer.clone();
16 
17         findAllPath(head.left, sum, c1, level + 1);
18         findAllPath(head.right, sum, c2, level + 1);
19     }
20 
21     private static void print(ArrayList<Integer> buffer, int level, int i2)
22     {
23         System.out.print("找到路径为:");
24         for (int i = level; i <= i2; i++)
25             System.out.print(buffer.get(i) + " ");
26         System.out.println();
27 
28     }

 

 

转载于:https://www.cnblogs.com/WayneZeng/archive/2013/04/09/3010893.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值