头图

title: Daily practice (19): print binary tree from top to bottom

categories:[Swords offer]

tags:[Daily practice]

date: 2022/02/15


Daily practice (19): print binary tree from top to bottom

The binary tree is printed in layers from top to bottom, the nodes of the same layer are printed from left to right, and each layer is printed to one line.

E.g:

Given a binary tree: [3,9,20,null,null,15,7],

 3
/ \
9  20
/   \
15   7

Return its hierarchical traversal result:

[
  [3],
  [9,20],
  [15,7]
]

hint:

Total number of nodes <= 1000

Source: LeetCode

Link: https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof

Note that to put each layer together, you need to maintain a level to save.

DFS remember to use reference &, otherwise you have to maintain a global variable.

Method 1: BFS

/**
 * 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<vector<int>> levelOrder(TreeNode* root) {
        queue<TreeNode*> q;
        q.push(root);
        vector<vector<int>> res;
        while (q.size()) {
            int size = q.size();
            vector<int> level;
            for (int i=0;i<size;i++) {
                TreeNode* rt = q.front();
                q.pop();
                if (!rt) {
                    continue;
                }
                level.push_back(rt->val);
                if (rt->left) {
                    q.push(rt->left);
                }
                if (rt->right) {
                    q.push(rt->right);
                }
            }
            if (level.size()!=NULL) {
                res.push_back(level);
            }
        }
        return res;
    }
};

Method 2: DFS

/**
 * 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<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        dfs(root, res, 0);
        return res;
    }
    void dfs(TreeNode* root,vector<vector<int>>& res,int level)
    {
        if (!root) {
            return;
        }
        if (level >= res.size()) {
            res.emplace_back(vector<int>());
        }
        res[level].emplace_back(root->val);
        dfs(root->left, res, level+1);
        dfs(root->right, res, level+1);
    }
};

加班猿
50 声望12 粉丝

记录一下生活的点滴,工作上遇到的问题以及学习上的各类笔记