94. Binary Tree Inorder Traversal
题目描述
Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
题解
左根右(left->root->right)。
用栈储存遍历得到结果序列。
Solution1:
/**
* 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>result;
stack<const TreeNode* > s;
const TreeNode *p = root;
while (!s.empty() || p != nullptr) {
if (p != nullptr) {
s.push(p);
p = p->left;
} else {
p = s.top();
s.pop();
result.push_back(p->val);
p = p->right;
}
}
return result;
}
};

本文介绍了一道LeetCode上的经典题目——二叉树中序遍历,并提供了一个非递归的解决方案。该方案使用栈来实现左根右的遍历顺序,详细解释了如何通过迭代方式获取节点值。
1138

被折叠的 条评论
为什么被折叠?



