-
Notifications
You must be signed in to change notification settings - Fork 30
/
BinaryTreeLevelOrderTraversal.cs
111 lines (95 loc) · 4.93 KB
/
BinaryTreeLevelOrderTraversal.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// Source : https://leetcode.com/problems/binary-tree-level-order-traversal/description/
// Author : codeyu
// Date : Wednesday, September 13, 2017 2:19:00 AM
/**********************************************************************************
*
* Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
*
*
* For example:
* Given binary tree [3,9,20,null,null,15,7],
*
* 3
* / \
* 9 20
* / \
* 15 7
*
*
*
* return its level order traversal as:
*
* [
* [3],
* [9,20],
* [15,7]
* ]
*
*
*
**********************************************************************************/
using System;
using System.Collections.Generic;
using Algorithms.Utils;
namespace Algorithms
{
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution102
{
public static IList<IList<int>> LevelOrder(TreeNode root)
{
var result = new List<IList<int>>();
if(root == null)
{
return result;
}
int h = height(root);
for (var i=1; i<=h; i++)
{
var levelResult = new List<int>();
GivenLevel(root, i, levelResult);
if(levelResult.Count == 0)
{
break;
}
result.Add(levelResult);
}
return result;
}
private static int height(TreeNode root)
{
if (root == null)
return 0;
else
{
int lheight = height(root.Left);
int rheight = height(root.Right);
if (lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}
private static void GivenLevel (TreeNode root ,int level, IList<int> levelResult)
{
if (root == null)
return;
if (level == 1)
{
levelResult.Add(root.Val);
}
else if (level > 1)
{
GivenLevel(root.Left, level-1, levelResult);
GivenLevel(root.Right, level-1, levelResult);
}
}
}
}