題目描述
從上往下打印出二叉樹的每個節點,同層節點從左至右打印。
解題思路:
剛開始看到這題愣了半天,本題實際上就是二叉樹的層次遍歷,深度遍歷可以用遞歸或者棧,而層次遍歷很明顯應該使用隊列。每次打印一個結點時,如果該結點有子結點,則將子結點放到隊列的末尾,接下來取出隊列的頭重複前面的打印動作,直到隊列中所有的結點都打印完畢。
python
# -*- 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
res = []
if not root :
return []
q = [root]
while len(q):
t = q.pop(0)
res.append(t.val)
if t.left:
q.append(t.left)
if t.right:
q.append(t.right)
return res
c++
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
};*/
#include<queue>
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
queue<TreeNode*> q;
vector<int> v;
if(root == NULL)
return v;
q.push(root);
while(!q.empty())
{root = q.front();
q.pop();
v.push_back(root->val);
if(root->left)
q.push(root->left);
if(root->right)
q.push(root->right);
}
return v;
}
};