问题描述
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
解决方案
/**
* 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) {
if( root == nullptr ) {
return { };
}
stack<TreeNode*> nodeStack;
nodeStack.push( root->right );
nodeStack.push( root->left );
vector<int> result{ root->val };
while( !nodeStack.empty() ) {
auto t = nodeStack.top();
nodeStack.pop();
if( t != nullptr ) {
result.push_back( t->val );
nodeStack.push( t->right );
nodeStack.push( t->left );
}
}
return result;
}
};
本文介绍了一种不使用递归的二叉树前序遍历方法,通过栈来实现节点的前序访问过程。具体地,文章提供了一个C++实现的例子,该例子首先将根节点的左子树压入栈中,然后是右子树,以此来确保正确的遍历顺序。
407

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



