Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
十分基础的树的算法,分为递归和非递归两种,先理解后记忆,如果应付考试或者面试可以直接背诵,中序和后序只是在代码中调整遍历顺序或递归前后条件;
直接上代码:
void preTraversal(struct TreeNode *root,int *res,int *count)
{
if(!root)
return;//递归两个条件之一:结束条件
else{
res[(*count)++] = root ->val;
if(root->left)
preTraversal(root->left,res,count);
if(root->right)
preTraversal(root->right,res,count);
}//递归的循环条件;
}//先序遍历先放根节点,然后依次左,右节点,根节点放入后将子树拆分成为左右子树,继续放入左子树根节点,进入循环;
int *preorderTraversal (struct TreeNode *root,int *returnSize){
if(!root)
return NULL;
int *res=(int*)malloc(1000*sizeof(int));
*returnSize=0;
preTraversal(root,res,returnSize);
return res;
}
非递归算法:运算速度更快,但修改的地方需要很好的理解:
int * preorderTraversal(struct treeNode * root,int * returnSize)
{
if(!root)
return NULL;//需要准备的类型如下:一个返回数组(存放遍历数字);一个栈(存放节点);一个计数器;一个栈的顶指针;
int * result=(int*)malloc(sizsof(int)*1000);
int index=0;
struct Treenode* stack[1000];
int head=0;
struct TreeNode *p=root;
while(p||head>0){
while(p){
result[index++]=p->val;
stack[head++]=p;
p=p->left;
}
if(head>0){
p=stack[--head];
p=p->right;
}
}//用一串数组加一个栈顶指针来代替栈,不需要入栈出栈函数,这是最大的亮点;
*returnSize=index;
return result;
}
Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?