zoukankan      html  css  js  c++  java
  • LeetCode OJ--Path Sum II **

    https://oj.leetcode.com/problems/path-sum-ii/

    树的深搜,从根到叶子,并记录符合条件的路径。

    注意参数的传递,是否需要使用引用。

    #include <iostream>
    #include <vector>
    using namespace std;
    struct TreeNode {
         int val;
         TreeNode *left;
         TreeNode *right;
         TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     };
    
    
    class Solution {
    public:
        vector<vector<int> > ans;
        vector<vector<int> > pathSum(TreeNode *root, int sum) 
        {
            ans.clear();
            if(root == NULL)
                return ans;
            vector<int> ansPiece;
            hasPathSum(root,sum,ansPiece);
            return ans;
        }
        void hasPathSum(TreeNode *root, int sum, vector<int> ansPiece) {
            //null
            if(root == NULL )
                return ;
    
            //leaf node
            if(root->left == NULL && root->right == NULL && root->val == sum)
            {
                ansPiece.push_back(root->val);
                vector<int> _ansPiece = ansPiece;
                ans.push_back(_ansPiece);
                return ;
            }
            if(root->left == NULL && root->right == NULL)
                return ;
    
            //not leaf node
            if(root->left ||root->right)
             {
                 ansPiece.push_back(root->val);
    
                if(root->left)
                    hasPathSum(root->left, sum - root->val,ansPiece);
    
                if(root->right)
                    hasPathSum(root->right, sum-root->val, ansPiece);  
             }
            return;
        }
    };
    
    int main()
    {
        TreeNode *n1 = new TreeNode(1);
        TreeNode *n2 = new TreeNode(-2);
        TreeNode *n3 = new TreeNode(-3);
        TreeNode *n4 = new TreeNode(1);
        TreeNode *n5 = new TreeNode(3);
        TreeNode *n6 = new TreeNode(-2);
        TreeNode *n7 = new TreeNode(4);
        TreeNode *n8 = new TreeNode(4);
        n1->left = n2;
        n1->right = n3;
        n2->left = n4;
        n2->right = n5;
        n3->left = n6;
        n3->right = n8;
        n4->left = n7;
        class Solution myS;
        myS.pathSum(n1,2);
        return 0;
    }
  • 相关阅读:
    57.纯 CSS 创作一双黑暗中的眼睛
    b1.关于em和px的关系
    56.纯 CSS 描述程序员的生活
    55.1拓展之边框border-width属性。
    55.纯 CSS 创作一个太阳、地球、月亮的运转模型
    54.纯 CSS 创作一副国际象棋
    53.纯 CSS 创作一个文本淡入淡出的 loader 动画
    52.纯 CSS 创作一个小球绕着圆环盘旋的动画
    ps
    05
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3792189.html
Copyright © 2011-2022 走看看