给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
我的思路:
其实就是先往左遍历,途中把所有的左节点压栈,走到尽头比如碰到NULL,然后再往右边走一下,看看节点是否为空,如果不为空就继续往左走,重复上述过程。
代码:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
vector<int> v;//存储结果集
TreeNode *cur = root;
while (cur != NULL || !s.empty())
{
while (cur != NULL)//当前节点不能为空
{
s.push(cur);//压栈
cur = cur->left;//继续往左走
}
cur = s.top();//此时左子树已经走到尽头,返回栈顶元素
s.pop(); //弹栈
v.push_back(cur->val);
cur = cur->right;//往右走一步
}
return v;
}
};