Binary Tree Preorder Traversal
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 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) {
vector<int> result;
stack<TreeNode *> nodeStack;
nodeStack.push(NULL);
while (root != NULL) {
result.push_back(root->val);
if (root->right != NULL)
nodeStack.push(root->right);
if (root->left != NULL) {
root = root->left;
}
else {
root = nodeStack.top();
nodeStack.pop();
}
}
return result;
}
};