Binary Tree Paths

题目描述:

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

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

["1->2->5", "1->3"]

看到树相关的题目,第一反应就是递归,下面是我的代码:

vector<string> binaryTreePaths(TreeNode* root) {
    vector<string> res;
    if (root != NULL)
    {
        char buf[20];
        sprintf(buf, "%d", root->val);
        string rootPath = buf;
        if (root->left == NULL && root->right == NULL)
        {
            res.push_back(rootPath);
        }
        else
        {
            if (root->left)
            {
                vector<string> leftPath;
                leftPath = binaryTreePaths(root->left);
                for (vector<string>::iterator it = leftPath.begin(); it != leftPath.end(); ++it)
                {
                    res.push_back(rootPath + "->" + *it);
                }
            }
            if (root->right)
            {
                vector<string> rightPath;
                rightPath = binaryTreePaths(root->right);
                for (vector<string>::iterator it = rightPath.begin(); it != rightPath.end(); ++it)
                {
                    res.push_back(rootPath + "->" + *it);
                }
            }
        }
    }
    return res;
}

想要简洁一点的,可以参考https://leetcode.com/discuss/52030/c-simple-4ms-recursive-solution

posted @ 2015-08-22 18:54  Sawyer Ford  阅读(170)  评论(0编辑  收藏  举报