ÉèΪÊ×Ò³ ¼ÓÈëÊÕ²Ø

TOP

c++ÖÐ*& ºÍ**& ·ûºÏ×÷ÓÃ˵Ã÷
2013-11-20 14:24:47 À´Ô´: ×÷Õß: ¡¾´ó ÖРС¡¿ ä¯ÀÀ:276´Î
Tags£º ·ûºÏ ×÷Óà ˵Ã÷

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
    For example:
    Given the below binary tree and sum = 22,
    5
    / \
    4   8
    /   / \
    11  13  4
    /  \    / \
    7    2  5   1
    return
    [
    [5,4,11,2],
    [5,8,4,5]
    ]
    ÎÊÌâÃèÊö£º¸ø¶¨Ò»¸ö¶þ²æÊ÷ºÍÒ»¸öÊý£¬ÕÒµ½ÔÚÕâ¸ö¶þ²æÊ÷ÖдӸù½Úµãµ½Ò¶×ӽڵ㷾¶ºÍµÈÓÚÕâ¸öÊý×ÖµÄËùÓз¾¶¡£
    Ç°Ãæ¶à´ÎÌáµ½£¬Óë¶þ²æÊ÷Ïà¹ØµÄÎÊÌ⣬¶à°ë¶¼¿ÉÒÔÓõݹ顣
    ¶ÔÓÚ±¾Ìâ¶øÑÔ£¬vector<vector<int> > pathSum£¨TreeNode *root, int sum£©º¯Êý·µ»ØÒÔrootΪ¸ùµÄ·¾¶ºÍµÈÓÚsumµÄËùÓз¾¶£¬ÄÇô¿ÉÒÔÕâôÏë
    pathSum£¨root->left, sum-£¨root->val£©£©·µ»Ø×ó×ÓÊ÷ÖкÍΪsum-£¨root->val£©µÄËùÓз¾¶£¬
    pathSum£¨root->right, sum-£¨root->val£©£©·µ»ØÓÒ×ÓÊ÷ÖкÍΪsum-£¨root->val£©µÄËùÓз¾¶£¬
    ÄÇôpathSum£¨root, sum£©¿ÉÒÔͨ¹ý½«root->val¼ÓÈëµ½ÉÏÃæËùÓз¾¶ÖУ¬È»ºó½«×óÓÒ×ÓÊ÷µÄ·¾¶½øÐкϲ¢µÃµ½¡£
    È»ºóÔÙÅжÏÁÙ½çÌõ¼þ¼´¿É¡£
    class Solution {
    public:
    vector<vector<int> > pathSum£¨TreeNode *root, int sum£© {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    if£¨root == NULL£©
    return vector<vector<int> >£¨£©£»
    if£¨root->left == NULL && root->right == NULL && root->val == sum£© {
    vector<vector<int> > vec;
    vector<int> ivec;
    ivec.push_back£¨sum£©£»
    vec.push_back£¨ivec£©£»
    return vec;
    }
    vector<vector<int> > vec1 = pathSum£¨root->left, sum-£¨root->val£©£©£»
    vector<vector<int> > vec2 = pathSum£¨root->right, sum-£¨root->val£©£©£»
    for£¨vector<vector<int> >::iterator iter = vec1.begin£¨£©£»
    iter != vec1.end£¨£©£» ++iter£© {
    £¨*iter£©¡£insert£¨£¨*iter£©¡£begin£¨£©£¬ root->val£©£»
    }
    for£¨vector<vector<int> >::iterator iter = vec2.begin£¨£©£»
    iter != vec2.end£¨£©£» ++iter£© {
    £¨*iter£©¡£insert£¨£¨*iter£©¡£begin£¨£©£¬ root->val£©£»
    vec1.push_back£¨*iter£©£»
    }
    return vec1;
    }
    };

¡¾´ó ÖРС¡¿¡¾´òÓ¡¡¿ ¡¾·±Ìå¡¿¡¾Í¶¸å¡¿¡¾Êղء¿ ¡¾ÍƼö¡¿¡¾¾Ù±¨¡¿¡¾ÆÀÂÛ¡¿ ¡¾¹Ø±Õ¡¿ ¡¾·µ»Ø¶¥²¿¡¿
·ÖÏíµ½: 
ÉÏһƪ£ºc++ primer×ܽáСµã ÏÂһƪ£ºC++ - ÖØÔØI/O²Ù×÷·ûµÄ..

ÆÀÂÛ

ÕÊ¡¡¡¡ºÅ: ÃÜÂë: (ÐÂÓû§×¢²á)
Ñé Ö¤ Âë:
±í¡¡¡¡Çé:
ÄÚ¡¡¡¡ÈÝ:

¡¤Linuxϵͳ¼ò½é (2025-12-25 21:55:25)
¡¤Linux°²×°MySQL¹ý³Ì (2025-12-25 21:55:22)
¡¤Linuxϵͳ°²×°½Ì³Ì£¨ (2025-12-25 21:55:20)
¡¤HTTP Åc HTTPS µÄ²î„ (2025-12-25 21:19:45)
¡¤ÍøÕ¾°²È«±ØÐ޿ΣºÍ¼ (2025-12-25 21:19:42)