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) {
ret.clear();
if(root != NULL)
preTrans(root);
return ret;
}
void preTrans(TreeNode * root){
ret.push_back(root->val);
if(root->left != NULL) preTrans(root->left);
if(root->right != NULL) preTrans(root->right);
}
private:
vector<int> ret;
};
当然还有非递归的方法,递归那么当然要使用到stack,其实这种方法写起来有点像是java中的递归的迭代器:
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ret;
if(root == NULL) return ret;
stack<TreeNode*> treeStk;
treeStk.push(root);
TreeNode * tmpNode;
while(!treeStk.empty()){
tmpNode = treeStk.top();
treeStk.pop();
ret.push_back(tmpNode->val);
if(tmpNode->left != NULL) treeStk.push(tmpNode->left);
if(tmpNode->right != NULL) treeStk.push(tmpNode->right);
}
return ret;
}
};
java版本的代码如下所示,首先是递归:
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<Integer>();
tranversal(root, ret);
return ret;
} public void tranversal(TreeNode root, List<Integer> ret){
if(root != null){
ret.add(root.val);
tranversal(root.left, ret);
tranversal(root.right, ret);
}
return;
}
}
然后是非递归的方式:
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> s = new Stack<TreeNode>();
List<Integer> ret = new ArrayList<Integer>();
s.push(root);
while(!s.isEmpty()){
TreeNode t = s.pop();
if(t == null)
continue;
ret.add(t.val);
s.push(t.right); //注意因为使用的是栈,所以应该先push right.
s.push(t.left);
}
return ret;
}
}