Leetcode 129. 求根到叶子节点数字之和

xiaoxiao2021-02-28  35

dfs,注意root空的情况

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

最新回复(0)