[leetcode] 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?
给定一棵二叉树,使用非递归的方法进行先序遍历。
用一个栈来保存回溯的节点,对于每个节点,都先访问栈顶元素,右儿子非空入栈,左儿子非空入栈的顺序进行,直到栈为空。
代码如下:
1 class Solution { 2 public: 3 vector<int> preorderTraversal(TreeNode *root) { 4 vector<int> res; 5 stack<TreeNode *> st; 6 TreeNode * p = root; 7 st.push(p); 8 if( root == NULL ) 9 { 10 return res; 11 } 12 while( st.size() != 0 ) 13 { 14 p = st.top(); 15 st.pop(); 16 res.push_back(p->val); 17 if( p->right != NULL ) 18 { 19 st.push(p->right); 20 } 21 if( p->left != NULL ) 22 { 23 st.push(p->left); 24 } 25 } 26 return res; 27 } 28 };