-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSumRootToLeftCsharp.cs
More file actions
65 lines (58 loc) · 1.55 KB
/
SumRootToLeftCsharp.cs
File metadata and controls
65 lines (58 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SumRootToLeftCsharp
{
/**
* Definition for binary tree
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
class SumRootToLeftCsharp
{
static void Main(string[] args)
{
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(3);
int result = SumNumbers(root);
Console.Write("Output is " + result);
}
public static int SumNumbers(TreeNode root)
{
int res = 0;
if (root == null) return res;
dfs(root, 0, ref res);
return res;
}
public static void dfs(TreeNode root, int cur, ref int res)
{
TreeNode l = root.left;
TreeNode r = root.right;
if (l == null && r == null)
{
cur = cur * 10 + root.val;
res += cur;
return;
}
cur=cur*10+root.val;
if(l!=null)
dfs(l,cur, ref res);
if(r!=null)
dfs(r,cur, ref res);
}
}
}