**《剑指offer》22:从上往下打印二叉树

题目描述

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


考点:宽度优先遍历

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> a;
        if(root  == NULL)
            return a;
        
        queue<TreeNode*> b;
        b.push(root);
        
        while(!b.empty())
        {
            TreeNode *t = b.front();
            b.pop();
            a.push_back(t -> val);
            if(t -> left != NULL)
                b.push(t -> left);
            if(t -> right != NULL)
                b.push(t -> right);
        }
        
        return a;
    }
};
Python实现:

思路:先将根节点放入一个列表b,并将根节点的值放入a中;然后将根节点的下一层节点放入另一个列表c,令b = c,做第一步的操作。如果b为空,则遍历结束。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回从上到下每个节点值列表,例:[1,2,3]
    def PrintFromTopToBottom(self, root):
        # write code here
        a = []
        res = []
        if root == None:
            return a
        
        b = [root]
        
        while b:
            c = []
            for i in b:
                if i.left != None:
                    c.append(i.left)
                if i.right != None:
                    c.append(i.right)
                res.append(i.val)
            b = c
        
        return res

猜你喜欢

转载自blog.csdn.net/w113691/article/details/80982743