Title
Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3],
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
Solution
/**
* 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> inorderTraversal(TreeNode* root) {
vector<int> v;
stack<TreeNode *> s;
TreeNode *p = root;
while(p || !s.empty()) {
//left node is not null, continue
while(p) {
s.push(p);
p = p->left;
}
//output this node, and then right node
if(!s.empty()) {
p = s.top();
int x = p->val;
s.pop();
v.push_back(x);
p = p->right;
}
}
return v;
}
};
runtime: 0ms
直接测试,通过。