-
Notifications
You must be signed in to change notification settings - Fork 0
/
144-BinaryTreePreorderTraversal.cs
44 lines (39 loc) · 1.26 KB
/
144-BinaryTreePreorderTraversal.cs
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
using Solution.Utils;
using System;
using System.Collections.Generic;
using System.Text;
namespace Solution
{
public class BinaryTreePreorderTraversalIterative
{
public static List<int> Solution(TreeNode<int> root)
{
List<int> result = new List<int>();
var stack = new Stack<TreeNode<int>>();
stack.Push(root);
while (stack.Count != 0)
{
var node = stack.Pop();
result.Add(node.Val);
if (node.Right != null) stack.Push(node.Right);
if (node.Left != null) stack.Push(node.Left);
}
return result;
}
}
public class BinaryTreePreorderTraversalRecursive
{
public static List<int> Solution(TreeNode<int> root)
{
return Preorder(root, new List<int>());
}
private static List<int> Preorder(TreeNode<int> root, List<int> nodes)
{
if (root == null) return nodes;
nodes.Add(root.Val);
if (root.Left != null) Preorder(root.Left, nodes);
if (root.Right != null) Preorder(root.Right, nodes);
return nodes;
}
}
}