Binary Tree Paths

来源:互联网 发布:sql 2005 编辑:程序博客网 时间:2024/05/16 12:49

Given a binary tree, return all root-to-leaf paths.


样例

Given the following binary tree:

   1 /   \2     3 \  5

All root-to-leaf paths are:

[  "1->2->5",  "1->3"]
/** * 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 the binary tree     * @return all root-to-leaf paths     */    vector<string> binaryTreePaths(TreeNode* root) {        // Write your code here        vector<string> result;        vector<TreeNode*> buf;        visit(root, buf, result);        return result;    }private:    void visit(TreeNode *root, vector<TreeNode*> &buf, vector<string> &result)    {        if (root == NULL)        {            return;        }        buf.push_back(root);        if (root->left == NULL && root->right == NULL)        {            string temp;            for (vector<TreeNode*>::iterator it = buf.begin(); it != buf.end(); it++)            {                if (temp.length() != 0)                {                    temp += "->";                }                char str[20];                sprintf(str, "%d", (*it)->val);                temp += str;            }            result.push_back(temp);        }        else        {            visit(root->left, buf, result);            visit(root->right, buf, result);        }        buf.pop_back();        return;    }};


0 0
原创粉丝点击