Given a binary tree, return the preorder traversal of its nodes' values.
// non-recursion version:
/**
* 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> solution;
// recursive is easy
// let's do it without recursive
// probably need to use stack
vector<int> preorderTraversal(TreeNode *root) {
if (root==NULL)
return solution;
stack<TreeNode *> mystack;
TreeNode * node;
mystack.push(root);
while (!mystack.empty()){
node = mystack.top();
mystack.pop();
if (node){
solution.push_back(node->val);
mystack.push(node->right);
mystack.push(node->left);
}
}
return solution;
}
};
本文介绍了一种使用栈实现的二叉树前序遍历的非递归方法。通过将二叉树节点压入栈中,然后不断弹出并访问节点值的方式,完成了对二叉树节点值的前序遍历。
385

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



