【举例让抽象具体化】从上到下打印二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ghscarecrow/article/details/81989801

此题出自牛客网的剑指offer专题

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

解题思路

其实这道题考察的是二叉树的层序遍历问题。我们可以借助一个队列来辅助我们完成该问题。首先先将根节点放进队列中,倘若此时队列不为空,则将该节点进行出队处理,同时将其值添加到数组中,接下来便进行两次判断,第一次判断其左子树是否为空,不为空则入队,右子树同理。然后不停地进行该循环直至队列为空。当队列为空时则说明该二叉树的所有结点均已添加到我们定义好的数组中。最后只需将该数组返回即可。

代码如下:

Java版本

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        
        ArrayList<Integer> result = new ArrayList<>();
        if(root==null){
            return result;
        }
        Deque<TreeNode> queque = new LinkedList<>();
        
        queque.add(root);
        while(!queque.isEmpty()){
            TreeNode t = queque.pop();
            result.add(t.val);
            if(t.left!=null){
                queque.add(t.left);
            }
            if(t.right!=null){
                queque.add(t.right);
            }
        }
        return result;
    }
}

C++版本

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    vector<int> PrintFromTopToBottom(TreeNode* root) {
        vector<int> result;
        TreeNode* temp;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty())
        {
            temp = q.front();
            q.pop();
            if(temp == NULL)
            {
                continue;
            }
            result.push_back(temp->val);
            q.push(temp->left);
            q.push(temp->right);
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/ghscarecrow/article/details/81989801
今日推荐