打印二叉树中所有和为某一值的路径
2014-07-20 16:02
288 查看
采用前序遍历二叉树,访问过程中保存路径上的结点,到达叶节点时,判断是否满足条件。切记每次左右子树的递归调用返回后,从路径中删除当前根节点。
#include <iostream> #include <vector> using namespace std; struct BiTreeNode{ int val; BiTreeNode* leftChild; BiTreeNode* rightChild; }; void FindPathMatchSum(BiTreeNode* root, int expectedSum, int& currentSum, vector<int>& path) { currentSum += root->val; path.push_back(root->val); if (root->leftChild == NULL && root->rightChild == NULL){ if (expectedSum == currentSum){ //print path for (int i = 0; i < path.size(); ++i) printf("%d ", path[i]); } return; } if (root->leftChild) FindPathMatchSum(root->leftChild, expectedSum, currentSum, path); if (root->rightChild) FindPathMatchSum(root->rightChild, expectedSum, currentSum, path); currentSum -= root->val; path.pop_back(); } void FindPath(BiTreeNode* root, int expectedSum){ if (root == NULL) return; vector<int> path; int currentSum = 0; FindPathMatchSum(root, expectedSum, currentSum, path); }
相关文章推荐
- 打印二叉树中路径和为某一值的所有路径
- 在二叉树中找出和为某一值的所有路径
- 二叉树中找出和为某一值的所有路径
- 题目:输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶结点所经过的结点形成一条路径。
- java实现输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径
- 程序员面试题目总结--树(一)【重建二叉树、二叉树的深度、树的子结构、二叉树中和为某一值得路径、从上往下打印二叉树】
- 打印二叉树的所有路径
- 257. Binary Tree Paths(打印二叉树所有路径)
- 剑指offer_输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径
- 在二叉树中找出和为某一值的所有路径
- 在二叉树中找出和为某一值的所有路径
- 打印二叉树中和为某一值的路径
- [程序员面试题精选100题]4.二叉树中和为某一值的所有路径
- 程序员面试100题(算法)之二叉树中找出和为某一值的所有路径(含二叉树前序创建、遍历)
- 给定一棵二叉树,每个结点包含一个值。打印出所有满足以下条件的路径: 路径上结点的值加起来等于给定的一个值。注意:这些路径不必从根结点开始。
- 【算法-java】打印出二叉树中结点值的和为输入整数的所有路径
- 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
- Company TengX 面试 笔试 : 打印 二叉树 指定值的所有路径
- 打印二叉树和为某一值的路径
- 打印二叉树所有的路径