【一天一道LeetCode】#257. Binary Tree Paths

一天一道LeetCode

本系列文章已全部上傳至我的github,地址:ZeeCoder‘s Github
歡迎大家關注我的新浪微博,我的新浪微博
歡迎轉載,轉載請註明出處

(一)題目

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. 需要考慮節點值爲負數的情況,要轉成string
  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> ret;
        string tmp;
        if(root!=NULL) dfsTreePaths(root,ret,tmp);
        return ret;
    }
    void dfsTreePaths(TreeNode* root,vector<string>& ret, string tmp)
    {
        if(root->left == NULL&& root->right==NULL) {//如果爲葉子節點就輸出
            char temp[10];
            sprintf(temp, "%d", root->val);//將整數轉換成string
            tmp += string(temp);
            ret.push_back(tmp);
            return;
        }
        char temp[10];
        sprintf(temp, "%d", root->val);//將整數轉換成string
        tmp += string(temp);
        tmp +="->";
        if(root->left !=NULL) dfsTreePaths(root->left,ret,tmp);//繼續搜索左子樹
        if(root->right !=NULL) dfsTreePaths(root->right,ret,tmp);//繼續搜索右子樹
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章