描述
给出一棵二叉树,返回其节点值的前序遍历。
您在真实的面试中是否遇到过这个题?
是
样例
给出一棵二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [1,2,3]
.
挑战
你能使用非递归实现么?
遍历二叉树使用递归十分简单:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: A Tree
* @return: Preorder in ArrayList which contains node values.
*/
vector<int> m_vector;
vector<int> preorderTraversal(TreeNode * root) {
// write your code here
if(root!=NULL)
search(root);
return m_vector;
}
void search(TreeNode *m_node){
m_vector.push_back(m_node->val);
if(m_node->left!=NULL)
search(m_node->left);
if(m_node->right!=NULL)
search(m_node->right);
}
};
采用非递归的方式,可以使用栈来辅助操作:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: A Tree
* @return: Preorder in ArrayList which contains node values.
*/
vector<int> preorderTraversal(TreeNode * root) {
// write your code here
stack<TreeNode*> m_stack;
vector<int> m_vector;
TreeNode * m_node=root;
if(root!=NULL)
m_stack.push(m_node);
while(!m_stack.empty()){
m_vector.push_back(m_node->val);
if(m_node->right!=NULL){
m_stack.push(m_node->right);
}
if(m_node->left!=NULL){
m_node=m_node->left;
}else{
m_node=m_stack.top();
m_stack.pop();
}
}
return m_vector;
}
};
但我第一次犯了错误思考了很久:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: A Tree
* @return: Preorder in ArrayList which contains node values.
*/
vector<int> preorderTraversal(TreeNode * root) {
// write your code here
stack<TreeNode> m_stack;
vector<int> m_vector;
TreeNode * m_node=root;
if(root!=NULL)
m_stack.push(*m_node);
while(!m_stack.empty()){
m_vector.push_back(m_node->val);
if(m_node->right!=NULL){
m_stack.push(*m_node->right);
}
if(m_node->left!=NULL){
m_node=m_node->left;
}else{
m_node=&m_stack.top();
m_stack.pop();
}
}
return m_vector;
}
};
至今不能明白为什么
m_stack.push
之后m_code的值会发生改变,希望有明白的同学可以不吝赐教。