问题:
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?
分析:
这道题要求我们对一棵二叉树进行前序遍历,如果是递归就比较简单,如果是迭代的话,因为考虑到前序遍历的特点(先当前再左再右),所以想到用stack这个结构,接下来就比较简单了。
代码:
/**
* Definition for a binary tree node.
* 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) {
stack<TreeNode*> nodes;
vector<int> nums;
if( root == NULL ){
return nums;
}
nodes.push(root);
while( !nodes.empty() ){
TreeNode* curNode = nodes.top();
nodes.pop();
nums.push_back(curNode->val);
//栈是后进先出,所以先插右节点,再插左节点
if( curNode->right != NULL ) {
nodes.push(curNode->right);
}
if( curNode->left != NULL ){
nodes.push( curNode->left );
}
}
return nums;
}
};