当前位置:   article > 正文

二叉树的遍历——层序遍历_完全二叉树的层序遍历

完全二叉树的层序遍历

一、之前写了二叉树的三种遍历方法:有先序遍历、中序遍历、后序遍历,这三种方法都是用递归的方式来遍历二叉树的。层序遍历则不是使用递归来遍历,而是使用队列的来实现遍历:

  1. void LevelTreeOrder(BTNode* root)
  2. {
  3.     Queue q;
  4.     QueueInit(&q);
  5.    
  6.     if(root)
  7.         QUueuePush(&q,root);
  8.     while(!EmptyQueue(&q))
  9. {
  10.     BTNode* front = QueueFront(&q);
  11.     printf("%d ",front->data);
  12.     QueuePop(&q);
  13.     if(front->left)
  14.         QueuePush(&q,front->left);
  15.     if(front->right)
  16.         QueuePush(&q,front->right);
  17. }
  18.     printf("\n");
  19.     QueueDestroy(&q);
  20. }

代码就是如上所示,前提是你要有一个写好的队列的代码。

二、我们可以使用层序遍历来判断完全二叉树

借助于上面的写好的层序遍历,我们可以写出

  1. void isTreeComplete(BTNode* root)
  2. {
  3.     Queue q;
  4.     QueueInit(&q);
  5.     if(root)
  6. QUueuePush(&q,root);
  7. while(!EmptyQueue(&q))
  8. {
  9.         BTNode* front = QueueFront(&q);
  10.         QueuePop(&q);
  11.         if(front==NULL)
  12.             break;
  13.         else{
  14.             QueuePush(front->left);
  15.             QueuePush(front->right);
  16.             }
  17. }
  18.     while(!EmptyQueue(&q))
  19. {
  20.         BTNode* front = QueueFront(&q);
  21.         QueuePop(&q);
  22.         if(front){
  23.             QueueDestroy(&q);
  24.             return false;}
  25.        
  26. }
  27. QueueDestroy(&q);
  28. return true;
  29. }

三、判断所给的树是不是对称的树

题目要求给你一棵树,需要你判断是不是一颗对称的树:

  1. bool _isSymmetric(struct TreeNode* root1,struct TreeNode* root2){
  2. if(root1 == NULL &&root2==NULL)
  3. return true;
  4. if(root1 == NULL || root2 ==NULL )
  5. return false;
  6. if(root1->val != root2->val)
  7. return false;
  8. return _isSymmetric(root1->left,root2->right)&&_isSymmetric(root1->right,root2->left);
  9. }
  10. bool isSymmetric(struct TreeNode* root){
  11. return !root || _isSymmetric(root->left,root->right);
  12. }

和之前写的isSameTree的思路还是很像的;

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/715986
推荐阅读
相关标签
  

闽ICP备14008679号