题目描述:
Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]1 \ 2 / 3 Output:[1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
迭代实现二叉树的前序遍历。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
if(root==NULL) return result;
stack<TreeNode*> s;
TreeNode* p=root;
while(p!=NULL||!s.empty())
{
if(p!=NULL)
{
result.push_back(p->val);
s.push(p);
p=p->left;
}
else
{
p=s.top()->right;
s.pop();
}
}
return result;
}
};
本文介绍了一种使用迭代方法实现二叉树前序遍历的算法,详细解释了如何通过栈来辅助完成遍历过程,并提供了一个具体的代码实现。
1114

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



