Advertisement
whitecatgsd

Untitled

Apr 24th, 2015
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. /**
  2.  * Definition for binary tree
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8.  * };
  9.  */
  10. class Solution { // Iteratively
  11. public:
  12.     vector<int> inorderTraversal(TreeNode *root) {
  13.         vector<int> result;
  14.        
  15.         if (!root) {
  16.             return result;
  17.         }
  18.        
  19.         std::stack<TreeNode*> nodeStack;
  20.         TreeNode *p = root;
  21.        
  22.         while (!nodeStack.empty() || p) {
  23.             if (p) {
  24.                 nodeStack.push(p);
  25.                 p = p->left;
  26.             } else {
  27.                 p = nodeStack.top();
  28.                 nodeStack.pop();
  29.                 result.push_back(p->val);
  30.                 p = p->right;
  31.                
  32.             }
  33.         }
  34.         return result;
  35.            
  36.     }
  37. };
  38.  
  39. class Solution { // Recursively
  40. public:
  41.     vector<int> inorderTraversal(TreeNode *root) {
  42.         vector<int> result;    
  43.         helper(root,result);
  44.         return result;
  45.     }
  46.     void helper(TreeNode *root, vector<int> &result){
  47.         if (root!=NULL){
  48.             helper(root->left,result);
  49.             result.push_back(root->val);
  50.             helper(root->right,result);
  51.         }
  52.     }
  53. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement