Thursday, July 21, 2016

257. Binary Tree Paths

This a problem of DFS over tree. The trick here is the termination for DFS should be the node is a leaf node instead of NULL, otherwise, you'll output duplicated path. Also need to be careful about the output format.

1:  /**  
2:   * Definition for a binary tree node.  
3:   * struct TreeNode {  
4:   *   int val;  
5:   *   TreeNode *left;  
6:   *   TreeNode *right;  
7:   *   TreeNode(int x) : val(x), left(NULL), right(NULL) {}  
8:   * };  
9:   */  
10:  class Solution {  
11:  public:  
12:    vector<string> binaryTreePaths(TreeNode* root) {  
13:      vector<string> res;  
14:      if (root == NULL) return res;  
15:      helper(root, "", res);  
16:      return res;  
17:    }  
18:    void helper(TreeNode* root, string path, vector<string> &res) {  
19:      if (root->left == NULL && root->right == NULL) {  
20:        res.push_back(path+to_string(root->val));  
21:        return;  
22:      }  
23:      if (path.empty()) {  
24:        if (root->left) helper(root->left, to_string(root->val)+"->", res);  
25:        if (root->right) helper(root->right, to_string(root->val)+"->", res);  
26:      } else {  
27:        if (root->left) helper(root->left, path+to_string(root->val)+"->", res);  
28:        if (root->right) helper(root->right, path+to_string(root->val)+"->", res);  
29:      }  
30:    }  
31:  };  

No comments:

Post a Comment