剑指offer:二叉树中和为某一值的路径
生活随笔
收集整理的這篇文章主要介紹了
剑指offer:二叉树中和为某一值的路径
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述:輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。
分析:路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。
用遞歸的思想去把和分解
代碼實現:
#include <iostream> #include <vector> using namespace std;typedef struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {} }Node;class Solution { public:vector<vector<int> > buffer;vector<int> tmp;vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {if(root==NULL)return buffer;tmp.push_back(root->val);if((expectNumber-root->val)==0 && root->left==NULL && root->right==NULL){buffer.push_back(tmp);}FindPath(root->left,expectNumber-root->val);FindPath(root->right,expectNumber-root->val);if(tmp.size()!=0)tmp.pop_back();return buffer;} };int main() {Node *tmp ;Node* root = new Node(10);tmp = new Node(5);root->left = tmp ;tmp = new Node(12);root->right = tmp;tmp = new Node(4);root->left->left = tmp;tmp = new Node(7);root->left->right = tmp;vector<vector<int>> ret;Solution s;ret = s.FindPath(root,22); return 0; }總結
以上是生活随笔為你收集整理的剑指offer:二叉树中和为某一值的路径的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于移动支付的一点知识
- 下一篇: 七号信令详细介绍