94. Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes’ values.
Example:
Input: [1,null,2,3]
1
2
/
3
Output: [1,3,2]
/**
* 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> vec;
// 此题不能使用递归算法来做,需要使用非递归算法
///
以下的这个算法的做法是错误的,会使得算法陷入死循环,
虽然大致的思路是对的,但是运行的结果是内存溢出
///
if (root) {
TreeNode* p = root;
std::stack<TreeNode*> sta;
sta.push(root);
while (!sta.empty()) {
p = sta.top();
if (p -> left != NULL) {
// 会在这里陷入死循环,出不来了。就题目中给出的例子来看
// 本来3已经在2之前输出了,但是处理到2的时候还是会将3再次
// 放入到栈里面,就这样,会陷入死循环,从而导致内存溢出
sta.push(p->left);
} else {
vec.push_back(p -> val);
p = p -> right;
sta.pop();
if (p)
sta.push(p);
}
}
}
return vec;
}
};
// 以下的程序的运行结果是正确的
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> vec;
// 此题不能使用递归算法来做,需要使用非递归算法
if (root) {
TreeNode* p = root;
std::stack<TreeNode*> sta;
while (p || !sta.empty()) {
if (p) {
sta.push(p);
p = p -> left;
} else {
vec.push_back(sta.top() -> val);
p = sta.top() -> right;
sta.pop();
}
}
}
return vec;
}
};