二叉树中和为某一值的路径

来源:互联网 发布:数据库市场占有率 2016 编辑:程序博客网 时间:2024/06/05 19:33
    题目:输入一棵二叉树和一个整数,打印出二叉树中节点值得和为输入整数的所有路径,从树的根节点开始往下一直到叶子节点所经过的节点形成一条路径。    解析:每次遍历到叶子节点时,判断当前路径是否等于给定的值。如果是,则存储这条路径到allPath中,如果不是,则遍历下一条路径。
//所有路径集合vector<vector<int>> allPath;//某条路径集合vector<int> path;vector<vector<int> > FindPath(TreeNode* root,int value){if(root == NULL)return allPath;findPath(root,value);return allPath;}void findPath(TreeNode* root,int value) {if(root == NULL)return;if(root->left == NULL && root->right == NULL){path.push_back(value);if(root->val == value){allPath.push_back(path);}}else{path.push_back(root->val);if(root->left != NULL){findPath(root->left,value - root->val);}if(root->right != NULL){findPath(root->right,value - root->val);}}path.pop_back();}
0 0