[LeetCode] Binary Tree Paths

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

解題思路:

這道題題意是返回二叉樹中所有從根到葉的路徑。用遞歸法做比較方便。

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章