(LeetCode 面试经典 150 题) 129. 求根节点到叶节点数字之和 (深度优先搜索dfs)
129. 求根节点到叶节点数字之和
思路:深度优先搜索dfs,时间复杂度0(n)。
C++版本:
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:int dfs(TreeNode * root,int u){if(root==nullptr) return 0;if(root->left==nullptr && root->right==nullptr) return u*10+root->val;int sum=0;return dfs(root->left,u*10+root->val)+dfs(root->right,u*10+root->val);}int sumNumbers(TreeNode* root) {return dfs(root,0);}
};
JAVA版本:
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {int dfs(TreeNode root,int u){if(root==null) return 0;if(root.left==null && root.right==null) return u*10+root.val;int sum=0;return dfs(root.left,u*10+root.val)+dfs(root.right,u*10+root.val);}public int sumNumbers(TreeNode root) {return dfs(root,0);}
}
GO版本:
/*** Definition for a binary tree node.* type TreeNode struct {* Val int* Left *TreeNode* Right *TreeNode* }*/
func sumNumbers(root *TreeNode) int {return dfs(root,0)
}
func dfs(root *TreeNode,u int) int{if root==nil {return 0}if root.Left==nil &&root.Right==nil {return u*10+root.Val}return dfs(root.Left,u*10+root.Val)+dfs(root.Right,u*10+root.Val);
}