/**
* 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<int> preorderTraversal(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<int> result;
stack<TreeNode*> nodeStack;
TreeNode* curNode = root;
while(curNode || !nodeStack.empty())
{
if(curNode) result.push_back(curNode->val);
//...process left recursive call
while(curNode)
{
nodeStack.push(curNode);
curNode = curNode->left;
if(curNode) result.push_back(curNode->val);
}
//..process the rest after left recursive call
if(!nodeStack.empty())
{
curNode = nodeStack.top();
nodeStack.pop();
curNode = curNode->right;
}
}
return result;
}
};[LeetCode]Binary Tree Preorder Traversal
最新推荐文章于 2022-07-19 12:03:10 发布
本文介绍了一种使用栈实现二叉树前序遍历的方法。通过迭代而非递归的方式,该算法有效地遍历了二叉树并返回节点值的序列。此方法适用于需要节省调用栈空间的应用场景。
384

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



