Binary Tree Paths 二叉树遍历

来源:互联网 发布:qq管家域名检测 编辑:程序博客网 时间:2024/06/06 01:41

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"]
/** * 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://int->string sprintf(buf, "%d", 100);//遍历的过程中记录之前的路径,一旦遍历到叶子节点便将该路径加入结果中//注意path要回溯,就相当于重新赋值    vector<string> binaryTreePaths(TreeNode* root) {                vector<string> res;        string path;        char t[256];        if(root!=NULL)        {            sprintf(t,"%d",root->val);            path=t;            solve(res,path,root);        }        return res;    }        void solve(vector<string> &res,string &path,TreeNode *root)    {        if(root->left==NULL && root->right==NULL)        {            res.push_back(path);            return ;        }        if(root->left)        {            char t[256];            sprintf(t,"%d",root->left->val);            string tmp=t;            string path1=path+"->";            path1=path1+tmp;                        solve(res,path1,root->left);        }        if(root->right)        {            char t[256];            sprintf(t,"%d",root->right->val);            string tmp=t;            string path2=path+"->";            path2=path2+tmp;                        solve(res,path2,root->right);        }    }};
0 0
原创粉丝点击