Leetcode 107: Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

 

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left;
 6  *     public TreeNode right;
 7  *     public TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public IList<IList<int>> LevelOrderBottom(TreeNode root) {
12          var result = new List<IList<int>>();
13         
14         if (root == null) return result;
15         
16         var q = new Queue<TreeNode>();
17         q.Enqueue(root);
18         var count = q.Count;
19         
20         while (q.Count > 0)
21         {
22             var r = new List<int>();
23             
24             for (int i = 0; i < count; i++)
25             {
26                 var t = q.Dequeue();
27                 r.Add(t.val);
28                 if (t.left != null) q.Enqueue(t.left);
29                 if (t.right != null) q.Enqueue(t.right);
30             }
31             
32             result.Insert(0, r);
33             count = q.Count;
34         }
35         
36         return result;
37     }
38 }

 

 

 

 
 
posted @ 2017-11-15 11:35  逸朵  阅读(122)  评论(0编辑  收藏  举报