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 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> vec;
if(root == NULL)
{
return vec;
}
stack<TreeNode*> st;
TreeNode *tmp = root;
st.push(tmp);
vec.push_back(tmp -> val);
while(!st.empty())
{
if(tmp -> left == NULL && tmp -> right == NULL)
{
st.pop();
if(st.empty())
{
break;
}
}
tmp = st.top();
if(tmp -> left != NULL)
{
TreeNode *t = tmp;
tmp = tmp -> left;
vec.push_back(tmp -> val);
st.push(tmp);
t -> left = NULL;
continue;
}
// if(st.empty())
// {
// break;
// }
tmp = st.top();
if(tmp -> right != NULL)
{
TreeNode *t = tmp;
tmp = tmp -> right;
vec.push_back(tmp -> val);
st.push(tmp);
t -> right = NULL;
continue;
}
}
return vec;
}
};
参考网上
/**
* 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> ivec;
if(root == NULL)
{
return ivec;
}
stack<TreeNode*> st;
st.push(root);
while(!st.empty())
{
TreeNode* tmp = st.top();
ivec.push_back(tmp -> val);
st.pop();
if(tmp -> right != NULL)
{
st.push(tmp -> right);
}
if(tmp -> left != NULL)
{
st.push(tmp -> left);
}
}
return ivec;
}
};