做一下简单二叉树遍历的题目:
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].
递归遍历比较简单,此处略;
非递归遍历:
/**
* 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) {
vector<int> value;
stack<TreeNode*> Stack;
if (root == NULL)
return value;
Stack.push(root);
while (!Stack.empty())
{
TreeNode *ptr = Stack.top();
Stack.pop();
value.push_back(ptr->val);
if (ptr->right != NULL)
Stack.push(ptr->right);
if (ptr->left != NULL)
Stack.push(ptr->left);
}
return value;
}
};