/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode left;
TreeNode right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
/
class Solution {
public:
vector inorderTraversal(TreeNode root) {
TreeNode current = root;
stack<TreeNode > temp;
vector result;
while(1){
while(current){
temp.push(current);
current = current->left;
}
if(!temp.empty()){
current = temp.top();
temp.pop();
result.push_back(current->val);
current = current->right;
}
else
break;
}
return result;
}
};
本文介绍了一种使用栈实现二叉树中序遍历的方法。通过不断将当前节点压入栈并移动到左子节点,直到左子节点为空。然后从栈顶弹出节点,访问其值,并转向右子节点,重复这一过程直到栈空且当前节点为null。这种方法有效地实现了二叉树的中序遍历。
1189

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



