You are given a binary tree (not necessarily BST) 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.

http://stackoverflow.com/questions/4591763/find-paths-in-a-binary-search-tree-summing-to-a-target-value

Traverse through the tree from the root and do a post-order gathering of all path sums. Use a hashtable at each node to store the possible paths rooted at a node and going down-only. Key is the path sum, value is the actual path. We can construct all paths going through a node from itself and its childrens' paths.

Here is psuedo-code that implements the above, but stores only the sums and not the actual paths. For the paths themselves, you need to store the end node in the hashtable (we know where it starts, and there's only one path between two nodes in a tree).

function findsum(tree, target)
# Traverse the children
if tree->left
findsum(tree.left, target)
if tree->right
findsum(tree.right, target) # Single node forms a valid path
tree.sums = {tree.value} # Add this node to sums of children
if tree.left
for left_sum in tree.left.sums
tree.sums.add(left_sum + tree.value)
if tree.right
for right_sum in tree.right.sums
tree.sums.add(right_sum + tree.value) # Have we formed the sum?
if target in tree.sums
we have a path # Can we form the sum going through this node and both children?
if tree.left and tree.right
for left_sum in tree.left.sums
if target - left_sum in tree.right.sums
we have a path # We no longer need children sums, free their memory
if tree.left
delete tree.left.sums
if tree.right
delete tree.right.sums

最新文章

  1. java操作数据库增删改查的小工具1--TxQueryRunner
  2. [HTML/CSS] ul元素居中处理
  3. Apache Rewrite 拟静态配置
  4. exp.validate.js
  5. 得分(Score,ACM/ICPC Seoul 2005,UVa 1585)
  6. seajs 使用 jquery插件
  7. Using OpenCV Java with Eclipse
  8. CentOS 7 安装JDK
  9. php中函数前加&符号的作用分解
  10. Android中bitmap的相关处理
  11. POJ 2774 Long Long Message(后缀数组)
  12. Linux基础(7)
  13. 自己定义View Controller转换动画
  14. No grammar constraints (DTD or XML schema).....两种解决方法
  15. python 爬虫与数据可视化--爬虫基础知识
  16. VUE 2.x SEO 优化问题 vue-meta-info && prerender-spa-plugin 配合使用
  17. centos 编译lantrn
  18. 【BZOJ1559】[JSOI2009]密码(AC自动机,动态规划,搜索)
  19. 深入php内核,从底层c语言剖析php实现原理
  20. Unix IPC之基于共享内存的计数器

热门文章

  1. SqlServer 高版本数据库 降级
  2. Strong AI Versus Weak AI
  3. Andrew Ng机器学习公开课笔记–Principal Components Analysis (PCA)
  4. 如何获取DIV的id
  5. nRF51822之pstorage使用摘要
  6. 兼容的获得event
  7. C/C++ 排序&&查找算法(面试)
  8. [LeetCode]题解(python):054-Spiral Matrix
  9. animate实现动画效果
  10. WPF 本周、本月、本季、本年的第一天与最后一天取法