题目
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?
求二叉树的中续遍历结果,用循环而不是递归
代码
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ret;
if(!root)
return ret;
stack<TreeNode*> s;
TreeNode *p = root;
while(p != 0 || !s.empty()) {
while(p != 0) {
s.push(p);
p = p -> left;
}
if(!s.empty()) {
p = s.top();
ret.push_back(p->val);
s.pop();
p = p->right;
}
}
return ret;
}
};