Please enable Javascript to view the contents

剑指office(二十四)二叉树中和为某一值的路径

 ·  ☕ 1 分钟  ·  🎅 YSL

题目描述

输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

示例1

输入

{10,5,12,4,7},22

返回值

[[10,5,7],[10,12]]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        if(root==NULL)
        {
            return result;
        }
        temp.push_back(root->val);
        if((expectNumber-root->val)==0&&root->left==NULL&&root->right==NULL)//叶结点
            result.push_back(temp);
        if(expectNumber-root->val<0)
            temp.pop_back();
        FindPath(root->left, expectNumber-root->val);
        FindPath(root->right, expectNumber-root->val);
        if(temp.size()>1)
            temp.pop_back();//栈回退
        return result;
    }
private:
    vector<int> temp;
    vector<vector<int>> result;
};