給定一個二叉樹,找出所有路徑中各節點相加總和等於給定 目標值
的路徑。
一個有效的路徑,指的是從根節點到葉節點的路徑。
樣例
給定一個二叉樹,和 目標值 = 5
:
1
/ \
2 4
/ \
2 3
返回:
[ [1, 2, 2], [1, 4] ]
思路:采用遞歸思想。分兩部分,一部分尋找二叉樹中的路徑(先序遍歷),一部分判斷路徑是否滿足要求。
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param root the root of binary tree * @param target an integer * @return all valid paths */ vector<vector<int>> vec; vector<int> temp; void Is_equal(vector<int> v,int ans){ //判斷路徑是否滿足要求; int sum=0; for(int i=0;i<v.size();i++){ sum+=v[i]; } if(sum==ans){ vec.push_back(v); } } vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) { // Write your code here //遍歷二叉樹,尋找路徑並存放入臨時容器temp中,並判斷是否滿足要求; if(root==NULL) { return vec; } temp.push_back(root->val); if(root->left!=NULL){ binaryTreePathSum(root->left,target); } if(root->right!=NULL){ binaryTreePathSum(root->right,target); } if(root->right==NULL&&root->left==NULL){ Is_equal(temp,target); } temp.erase(temp.begin()+temp.size()-1);//清空temp容器,空間和元素都清空; return vec; } };