跳至主要內容

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

T4mako算法深度优先二叉树小于 1 分钟

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

中等

题目描述open in new window

解法:dfs

class Solution {
    int res = 0;

	public int sumNumbers(TreeNode root) {
		dfs(root, 0);
		return res;
	}

	public void dfs(TreeNode node, int sum) {
		sum = sum * 10 + node.val;
		if (node.left == null && node.right == null) {
			res += sum;
		} else if (node.left == null) {
			dfs(node.right, sum);
		} else if (node.right == null) {
			dfs(node.left, sum);
		} else {
			dfs(node.right, sum);
			dfs(node.left, sum);
		}
	} 
}
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.5