Please enable Javascript to view the contents

剑指office(二十二)从上往下打印二叉树

 ·  ☕ 1 分钟  ·  🎅 YSL

题目描述

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

示例1

输入

{5,4,#,3,#,2,#,1}

返回值

[5,4,3,2,1]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*
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;
        if(root==NULL)
            return result;
        result.push_back(root->val);
        PrintLeftToRight(result,root);
        return result;
    }
    void PrintLeftToRight(vector<int>&result,TreeNode* root)
    {
         if(root==NULL||root->left==NULL&&root->right==NULL)
            return;
        if(root->left)
            result.push_back(root->left->val);
        if(root->right)
            result.push_back(root->right->val);
        PrintLeftToRight(result,root->left);
        PrintLeftToRight(result,root->right);
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*
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;
        if(root==NULL)
            return result;
        queue<TreeNode*> nodeQ;
        nodeQ.push(root);
        while(!nodeQ.empty())
        {
            TreeNode* cur = nodeQ.front();
            nodeQ.pop();
            result.push_back(cur->val);
            if(cur->left)nodeQ.push(cur->left);
            if(cur->right)nodeQ.push(cur->right);
        }
        return result;
    }
   
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*
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;
        if(root==NULL)
            return result;
        queue<TreeNode*> nodeQ;
        nodeQ.push(root);
        int level = 0;
        while(!nodeQ.empty())
        {
           int qS = nodeQ.size();
            while(qS--)
            {
                TreeNode* cur = nodeQ.front();
                nodeQ.pop();
                result.push_back(cur->val);
                if(cur->left)nodeQ.push(cur->left);
                if(cur->right)nodeQ.push(cur->right);
            }
            level++;
        }
        return result;
    }
   
};