606. Construct String from Binary Tree(Tree)

链接:https://leetcode.com/problems/construct-string-from-binary-tree/

题目:构造先序遍历字符串

思路:对于每个节点,5种情况

NULL         1              1                1                    1        
                           /                  \                  / \  
                          2                    3                2   3
直接返回     返回1      返回1(2)           返回1()(3)           返回1(2)(3)

代码:

class Solution {
public:
    string Int_String(int val){
           string ret = "";
           int v = val;
           if(val ==0 ) return "0";
           if(val < 0) val = -val;
        
           while(val) {
                ret = (char) (val % 10 +  '0')+ ret;
                val = val / 10;
           }
           if(v <0) ret = '-' + ret;
        
           return ret;
    }
    
    void pre(TreeNode* t , string *str){
           if(!t) return;
           (*str) = (*str) + Int_String(t->val);
            
           if(t->left){
              (*str) += '(';
              pre(t->left,str);
              (*str) += ')';
           }
        
           if(t->right){
               
              if(!t->left) {
                  (*str) += "()";
              }
              (*str) += '(';
              pre(t->right,str);
              (*str) += ')';
           }       
    }
    
    string tree2str(TreeNode* t) {
           string ret = "";
           pre(t,&ret);
           return ret;
    }
};

你可能感兴趣的:(606. Construct String from Binary Tree(Tree))