[leetcode] 257. Binary Tree Paths

来源:互联网 发布:c语言 设备端接入 编辑:程序博客网 时间:2024/06/07 20:27

Question :

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

Solution :

主要要做的就是遍历一棵树,不过要记录遍历时候遇到的值,这里使用dfs来完成遍历并记录沿途的值。

/** * 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> ret;        if(root == NULL) {            return ret;        }        string root_val = to_string(root->val);        dfs(ret, root, root_val);        return ret;    }    void dfs(vector<string> & v, TreeNode* root, string str){        if(root->left == NULL && root->right == NULL){            v.push_back(str);            return;        }        if(root->left != NULL) {            string val_str = str + "->" + to_string(root->left->val);            dfs(v, root->left, val_str);        }        if(root->right != NULL) {            string val_str = str + "->" + to_string(root->right->val);            dfs(v, root->right, val_str);        }    }};
原创粉丝点击