LEETCODE-二叉树的前序遍历

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?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值