剑指offer从上到下打印二叉树I(C++/Java双重实现)

1.问题描述

在这里插入图片描述

2.问题分析

本题我们可以使用队列来做,我们首先把树的每一层结点从左到右进入一个队列,然后再按照队列的顺序,那么这个时候二叉树就已经按照层序的方式依次存入队列,再一个一个的取出来即可

3.代码实现

3.1C++代码

/**
 * 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> levelOrder(TreeNode* root) {
        if(root==NULL)
        return {};
        vector<int> vec;
        int front=0;
        int rear=0;
        TreeNode* a[1010];
        a[rear++]=root;
        while(front<rear)
        {
              TreeNode *p;
              p=a[front++];
              vec.push_back(p->val);
              if (p->left!=NULL) {
              a[rear++]=p->left;}
              if (p->right!=NULL) {
              a[rear++]=p->right;}
        }
        return vec;

    }
};

3.2Java代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] levelOrder(TreeNode root) {
      if(root==null)
      return new int[0];
      int arr[]=new int [1010]; 
        int front=0;
        int rear=0;
        int cnt=0;
        TreeNode a[] =new TreeNode[1010];
        a[rear++]=root;
        while(front<rear)
        {
              TreeNode p;
              p=a[front++];
              arr[cnt++]=p.val;
              if (p.left!=null) {
              a[rear++]=p.left;}
              if (p.right!=null) {
              a[rear++]=p.right;}
        }
        int b[]=new int [cnt];
        int n=0;
        for(int t:arr)
        {
            if(n<cnt)
            b[n++]=t;
        }
        return b;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45737068/article/details/107797669