Neat Solution Using deque


  • 0
    D

    /**

    • 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<int> preorderTraversal(TreeNode
      root) {

       TreeNode* head = root;
       vector<int> result;
       
       if(!root)
           return result;
       
       std::deque<TreeNode*> traversal;
       traversal.push_back(head);
       while(!traversal.empty())
       {
           head = traversal.at(0);
           traversal.pop_front();
           result.push_back(head->val);
           if(head->right)
               traversal.push_front(head->right);
           if(head->left)
               traversal.push_front(head->left);
           
       }
       
       return result;
      

      }
      };


Log in to reply
 

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