[LeetCode] Binary Tree Level Order Traversal in Objective C

in #leetcode8 years ago
typedef struct {
     int value;
    struct TreeNode *left;
    struct TreeNode *right;
 } TreeNode;
  
-(NSMutableArray *)levelOrder:(TreeNode *)treeNode
{
   NSMutableArray *levelOrderArray = [NSMutableArray array];
   if (treeNode == nil) return levelOrderArray;
  
   NSMutableArray *queue = [NSMutableArray array];
   [queue addObject: treeNode];
   while (queue.count != 0) {
     NSMutableArray *eachLevelArray = [NSMutableArray array];
     int size = queue.count;
     for (int i = 0; i<size; i++) {
        treeNode *node = [queue firstObject];
        [queue removeObjectAtIndex: 0]; 
        [eachLevelArray addObject: node];
        if (node.left)  {
          [queue addObject: node.left];
        }
        if (node.right) {
          [queue addObject: node.right];
        }
     }
     [levelOrderArray addObject: eachLevelArray];
   }
  return levelOrderArray;
}

Coin Marketplace

STEEM 0.18
TRX 0.16
JST 0.029
BTC 76470.55
ETH 3079.00
USDT 1.00
SBD 2.62