【LeetCode】257. Binary Tree Paths

Binary Tree Pathsnode

Given a binary tree, return all root-to-leaf paths.this

For example, given the following binary tree:spa

 

   1
 /   \
2     3
 \
  5

 

All root-to-leaf paths are:3d

["1->2->5", "1->3"]

 

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

 

深度優先遍歷,每遇到葉節點,將棧中路徑記錄下來,最後將全部路徑轉成所需格式blog

/**
 * 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> path;
        if(root == NULL)
            return path;
        vector<vector<int> > pathv;    
        unordered_map<TreeNode*, bool> visited;
        stack<TreeNode*> stk;
        stk.push(root);
        visited[root] = true;
        if(root->left == NULL && root->right == NULL)
            save(pathv, stk);
        while(!stk.empty())
        {
            TreeNode* top = stk.top();
            if(top->left && visited[top->left] == false)
            {
                stk.push(top->left);
                visited[top->left] = true;
                if(top->left->left == NULL && top->left->right == NULL)
                    save(pathv, stk);
                continue;
            }
            if(top->right && visited[top->right] == false)
            {
                stk.push(top->right);
                visited[top->right] = true;
                if(top->right->left == NULL && top->right->right == NULL)
                    save(pathv, stk);
                continue;
            }
            stk.pop();
        }
        return convert(pathv);
    }
    void save(vector<vector<int> >& pathv, stack<TreeNode*> stk)
    {
        vector<int> cur;
        while(!stk.empty())
        {
            TreeNode* top = stk.top();
            cur.push_back(top->val);
            stk.pop();
        }
        reverse(cur.begin(), cur.end());
        pathv.push_back(cur);
    }
    vector<string> convert(vector<vector<int> >& pathv)
    {
        vector<string> path;
        for(int i = 0; i < pathv.size(); i ++)
        {
            string cur;
            cur += to_string(pathv[i][0]);
            for(int j = 1; j < pathv[i].size(); j ++)
            {
                cur += "->";
                cur += to_string(pathv[i][j]);
            }
            path.push_back(cur);
        }
        return path;
    }
};

相關文章
相關標籤/搜索