iterative solution similar to BFS method


  • 0
    W

    /**

    • Definition for a binary tree node.

    • struct TreeNode {

    • int val;
      
    • TreeNode *left;
      
    • TreeNode *right;
      
    • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
      
    • };
      /
      class Solution {
      public:
      vector<vector<int>> levelOrder(TreeNode
      root) {
      vector<vector<int>> res;
      if (root == NULL)
      return res;

       int currentlevelnodesnum = 1;
       queue <TreeNode*> traversednodes;
       traversednodes.push (root);
       
       while (!traversednodes.empty()){
           int temp = 0;
           vector<int> currentnodes;
           
           for (int i=0 ; i<currentlevelnodesnum ; i++){
               TreeNode* thisnode = traversednodes.front();
               currentnodes.push_back(thisnode->val);
               if (thisnode->left != NULL){
                   traversednodes.push(thisnode->left);
                   temp++;
               }
               if (thisnode->right != NULL){
                   traversednodes.push(thisnode->right);
                   temp++;
               }
               traversednodes.pop();
           }
           res.push_back(currentnodes);
           currentlevelnodesnum = temp;
           
       }
       
       return res;
      

      }
      };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.