码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ 之 Binary Tree Paths(二叉树路径)

时间:2015-08-31 15:16:29      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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"]

思路:

前序递归即可。

代码1:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) 
    {
        vector<string> result;
        if(root == NULL)
            return result;
        string path;
        binaryTreePaths(root , result , path);
        return result;
    }
    void binaryTreePaths(TreeNode* root , vector<string> &result , string path) 
    {
        if(root == NULL)
            return;
        if(path.empty())
            path += to_string(root->val);
        else
        {
            path += "->";
            path += to_string(root->val);
        }
        if(root->left == NULL && root->right == NULL)
        {
            result.push_back(path);
            return;
        }

        binaryTreePaths(root->left , result , path);
        binaryTreePaths(root->right , result , path);
    }
};


代码2:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) 
    {
        vector<string> result;
        if(root == NULL)
            return result;
        string path;
        binaryTreePaths(root , result , path);
        return result;
    }
    void binaryTreePaths(TreeNode* root , vector<string> &result , string path) 
    {
        if(root == NULL)
            return;

        if(root->left == NULL && root->right == NULL)
        {
            result.push_back(path + to_string(root->val));
            return;
        }

        binaryTreePaths(root->left , result , path + to_string(root->val) + "->");
        binaryTreePaths(root->right , result , path + to_string(root->val) + "->");
    }
};


版权声明:转载请注明出处。

LeetCode OJ 之 Binary Tree Paths(二叉树路径)

标签:

原文地址:http://blog.csdn.net/u012243115/article/details/48133743

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!