Lintcode---二叉樹的路徑和


給定一個二叉樹,找出所有路徑中各節點相加總和等於給定 目標值 的路徑。

一個有效的路徑,指的是從根節點到葉節點的路徑。

樣例

給定一個二叉樹,和 目標值 = 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;
  
    }
};
 
          

 

 
         


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM