Last active
December 10, 2015 08:08
-
-
Save pdu/4405450 to your computer and use it in GitHub Desktop.
Given a binary tree, return the inorder traversal of its nodes' values.
http://www.leetcode.com/onlinejudge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stack> | |
using namespace std; | |
/** | |
* Definition for binary tree | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
vector<int> inorderTraversal(TreeNode *root) { | |
vector<int> ret; | |
if (root == NULL) { | |
return ret; | |
} | |
stack<TreeNode*> s; | |
TreeNode* cur = root; | |
while (!s.empty() || cur != NULL) { | |
if (cur == NULL) { | |
cur = s.top(); | |
ret.push_back(cur->val); | |
s.pop(); | |
cur = cur->right; | |
} | |
else { | |
s.push(cur); | |
cur = cur->left; | |
} | |
} | |
return ret; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for binary tree | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
vector<int> inorderTraversal(TreeNode *root) { | |
vector<int> ret; | |
if (root == NULL) { | |
return ret; | |
} | |
vector<int> left = inorderTraversal(root->left); | |
vector<int> right = inorderTraversal(root->right); | |
ret.insert(ret.end(), left.begin(), left.end()); | |
ret.push_back(root->val); | |
ret.insert(ret.end(), right.begin(), right.end()); | |
return ret; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment