原题:
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?
首先回顾下什么是二叉树先序遍历:根节点在左右节点之前被访问。
/**
* 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> pre,left,right;
if (root==NULL) return pre;
pre.push_back(root->val);
left = preorderTraversal(root->left);
if (root->left==NULL) ;
else for (int i=0; i<left.size(); i++)
pre.push_back(left[i]);
right = preorderTraversal(root->right);
if (root->right==NULL) ;
else for (int i=0; i<right.size(); i++)
pre.push_back(right[i]);
return pre;
}
};
AC啦!本题还挺简单,选用了最偷懒的递归算法> /// <。