129. Sum Root to Leaf Numbers

    xiaoxiao2021-03-25  246

    DFS搜索求和

    /** * 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: //temp=0;sum=0 void dfs(int& temp,int& sum,TreeNode* root) { if(root==NULL) return; else { temp=temp*10+root->val; if(root->left==NULL&&root->right==NULL) sum+=temp; else { if(root->left!=NULL) dfs(temp,sum,root->left); if(root->right!=NULL) dfs(temp,sum,root->right); } temp=temp/10; return; } } int sumNumbers(TreeNode* root) { int temp=0; int sum=0; dfs(temp,sum,root); return sum; } };
    转载请注明原文地址: https://ju.6miu.com/read-368.html

    最新回复(0)