LeetCode 257:Binary Tree Paths

来源:互联网 发布:linux dd iso disk 编辑:程序博客网 时间:2024/05/07 08:01

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 /   \2     3 \  5
所有根节点到叶节点的路径为
["1->2->5", "1->3"]

/** * 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> vec;        string temp;        FindPaths(root,vec,temp);        return vec;    }    void FindPaths(TreeNode* root,vector<string>& vec,string temp)    {        if(!root) return;        char c[2];        sprintf(c,"%d",root->val);        temp.append(c);        if(root->left||root->right) temp.append("->");        else vec.push_back(temp);        FindPaths(root->left,vec,temp);        FindPaths(root->right,vec,temp);    }};


按道理,树的遍历应该不难的,数据结构也有讲过。可是因为我当时没怎么学好,导致所有与树有关的题基本都跳过去了。。。现在正在慢慢补回来。哎,加油吧



0 0
原创粉丝点击