1. 程式人生 > >Leetcode 314: Binary Tree Vertical Order Traversal

Leetcode 314: Binary Tree Vertical Order Traversal

color put rom sorted nbsp nod out eno key

Given a binary tree, return the vertical order traversal of its nodes‘ values. (ie, from top to bottom, column by column).

If two nodes are in the same row and column, the order should be from left to right.

Examples:

  1. Given binary tree [3,9,20,null,null,15,7],
       3
      / /   9  20
        /   /    15   7
    

    return its vertical order traversal as:

    [
      [9],
      [3,15],
      [20],
      [7]
    ]
    
  2. Given binary tree [3,9,8,4,0,1,7],
         3
        /   /     9   8
      /\  / /  \/   4  01   7
    

    return its vertical order traversal as:

    [
      [4],
      [9],
      [3,0,1],
      [8],
      [7]
    ]
    
  3. Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5] (0‘s right child is 2 and 1‘s left child is 5),
         3
        /   /     9   8
      /\  / /  \/   4  01   7
        /   /     5   2
    

    return its vertical order traversal as:

    [
      [4],
      [9,5],
      [3,0,1],
      [8,2],
      [7]
    ]
    

 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 Node 11 { 12 public TreeNode node; 13 public int column; 14 15 public Node(TreeNode n, int c) 16 { 17 node = n; 18 column = c; 19 } 20 } 21 22 public class Solution { 23 public IList<IList<int>> VerticalOrder(TreeNode root) { 24 var result = new List<IList<int>>(); 25 if (root == null) return result; 26 27 var dict = new SortedDictionary<int, IList<int>>(); 28 29 // for this problem, we need to use BFS instead of DFS, otherwise we will always output left tree nodes first instead of top to bottom 30 var queue = new Queue<Node>(); 31 queue.Enqueue(new Node(root, 0)); 32 33 while (queue.Count > 0) 34 { 35 var node = queue.Dequeue(); 36 37 if (!dict.ContainsKey(node.column)) 38 { 39 dict[node.column] = new List<int>(); 40 } 41 42 dict[node.column].Add(node.node.val); 43 44 if (node.node.left != null) 45 { 46 queue.Enqueue(new Node(node.node.left, node.column - 1)); 47 } 48 49 if (node.node.right != null) 50 { 51 queue.Enqueue(new Node(node.node.right, node.column + 1)); 52 } 53 } 54 55 foreach(var pair in dict) 56 { 57 result.Add(pair.Value); 58 } 59 60 return result; 61 } 62 }

Leetcode 314: Binary Tree Vertical Order Traversal