LeetCode【sum-root-to-leaf-numbers】

思路:

二叉树的先序遍历,加上字符串与数字之间的转换

/*思路:
二叉树的先序遍历*/
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
    public:
    int sumNumbers(TreeNode *root) {
        if (root == NULL)
            return 0;
        int res = 0;
        string tmp = "";
        preSearch(root, res, tmp);
        return res;
    }
    void preSearch(TreeNode *root, int &res, string &tmp)
    {
        if (root->left==NULL && root->right==NULL)
        {
            /*转换成数字*/
            string strN;
            int n;
            stringstream ss;
            ss << root->val;
            ss >> strN;
            int tmpSize = tmp.size();
            tmp += strN;
            ss.clear();			//再次使用时,需清空
            ss << tmp;
            ss >> n;
            res += n;
            /*返回时要将tmp复原*/
            tmp = tmp.substr(0, tmpSize);
            return;
        }
        stringstream ss;
        string n;
        /*转换成字符串*/
        ss << root->val;
        ss >> n;
        int tmpSize = tmp.size();
        tmp += n;
        if (root->left != NULL)
            preSearch(root->left, res, tmp);
        if (root->right != NULL)
            preSearch(root->right, res, tmp);
        /*字符串裁剪*/
        tmp = tmp.substr(0, tmpSize);           //遍历完再返回以往的状态
    }
};

int main()
{
    TreeNode a(1);
    TreeNode b(2);
    TreeNode c(3);
    a.left = &b;
    a.right = &c;
    Solution S;
    cout << S.sumNumbers(&a) << endl;
    system("pause");

    return 0;
}

猜你喜欢

转载自blog.csdn.net/zishengzheng/article/details/81673379