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?
Subscribe to see which companies asked this question.
题意:给定二叉树,要求返回其前序遍历各结点值。尝试递归,可否使用迭代完成?
①递归(Recursive):利用典型递归思路完成前序遍历结点,定义容器存储结点值以便输出。具体代码如下:
/**
* 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> preorderTrav; //定义容器存储结点值
vector<int> preorderTraversal(TreeNode* root) {
if(root==NULL)
return preorderTrav;
else{
preorderTrav.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
return preorderTrav;
}
};
②迭代(
iteratively
):
<span style="font-family:Times New Roman;">vector<int> preorderTraversal(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<int> preorderTrav;
stack<TreeNode*> stk;
if(root != NULL)
{
stk.push(root);
while(!stk.empty())
{
root = stk.top();
stk.pop();
preorderTrav.push_back(root->val);
if(root->right) stk.push(root->right);
if(root->left) stk.push(root->left);
}
}
return preorderTrav;
} </span>
<span style="font-family:Times New Roman;">注意容器及栈定义,以上两种方法精简地将前序遍历获取结点值。</span>