leetcode_257. 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"]
就是一個深搜,關鍵點是,什麼時候把搜到的加上去。它這個是每個葉子都有一條深搜的道路。也就是在遞歸的時候就將結點加上去了,於是就有了所有的道路。當到葉子的時候把這個當前的道路加到要輸出的總和中,然後繼續下面的遞歸。

然後要注意的是他給的root可能是空的,要先判斷一下。

還有就是int要轉成string,中間還要加->


貼代碼:

/**
 * 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> outstring;
        if(root==NULL) return outstring;
        
        search(outstring,root,to_string(root->val));
        return outstring;
    }
    void search(vector<string>&outstring, TreeNode* root, string value){
        if(root->left==NULL && root->right == NULL){
            outstring.push_back(value);
        }
        if(root->left != NULL){
            search(outstring, root->left, value + "->" + to_string(root->left->val));
        }
        if(root->right != NULL){
            search(outstring, root->right, value + "->" + to_string(root->right->val));
        }
        return;
    }
    
};


發佈了39 篇原創文章 · 獲贊 0 · 訪問量 4872
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章