题解 | #二叉树的中序遍历#
二叉树的中序遍历
http://www.nowcoder.com/practice/0bf071c135e64ee2a027783b80bf781d
面试的时候遇到这道题了,没写出来,发现还是有很讨厌的小细节的。。。
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型vector
*/
vector<int> inorderTraversal(TreeNode* root) {
// write code here
// 用递归的方法实现其中序遍历
// 用非递归的方法解决中序遍历的问题,需要用一个栈来模拟递归的过程,用栈来存储将要遍历的内容,只遍历栈中的内容
if (!root) return res;
TreeNode *p = root;
stack<TreeNode *> stk;
while (p || !stk.empty()) {
if (p) { // 只要存在,就加入栈,因为只访问栈中的元素
stk.push(p);
p = p->left;
} else {
p = stk.top();
stk.pop();
res.push_back(p->val);
p = p->right; // 只访问弹出的元素值,并不使用其左指针
}
}
return res;
}
private:
vector<int> res;
};
查看9道真题和解析
海康威视公司福利 1125人发布