题目:
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?
思路:
对于树这种数据结构,递归是解决其问题的天然灵丹妙药。然后本题蛋疼的是不让用递归,只能用迭代。那么就需要想到另外一种不错的数据结构:栈!对于中序遍历而言,我们首先从根节点开始,将所有左子树上的节点都压入栈中;然后取出栈顶元素并输出。之后需要判断栈顶元素的右孩子是否为空,如果不为空,则需要将右孩子连同它的所有沿着左子树的节点压入栈中。这样处理直到栈为空,我们就完成了对于一棵树的中序遍历。
代码:
/**
* 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> ret;
stack<TreeNode*> s;
if (root == NULL) {
return ret;
}
TreeNode *node= root;
while (node) {
s.push(node);
node = node->left;
}
while (!s.empty()) {
node = s.top();
s.pop();
ret.push_back(node->val);
node = node->right;
while (node) {
s.push(node);
node = node->left;
}
}
return ret;
}
};
本文介绍了一种不使用递归的二叉树中序遍历方法,通过栈来实现节点的访问顺序。详细解释了算法的流程,并提供了完整的C++代码实现。

328

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



