/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
TreeNode* cur = root;
TreeNode* top;
vector<int> res;
if (root == NULL) return res;
while (!st.empty() || cur != NULL)
{
/* 从根节点到最左下角 */
while (cur != NULL)
{
st.push(cur);
cur = cur->left;
}
top = st.top();
st.pop();
res.push_back(top->val);
if (top->right != NULL)
{
cur = top->right;
continue;
}
}
return res;
}
};
LeetCode94. 二叉树的中序遍历(非递归实现)
于 2024-06-04 10:23:28 首次发布