Skip to the content.

从上往下打印二叉树


Contact me:

Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub


来自牛客 剑指offer

题目描述

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

queue<TreeNode*> q;
vector<int> v;
vector<int> PrintFromTopToBottom(TreeNode* root) {
    if (root) {
        v.push_back(root->val);
        q.push(root->left);
        q.push(root->right);
    }
    if (q.size() > 0) {
        TreeNode* node = q.front();
        q.pop();
        PrintFromTopToBottom(node);
    }
    return v;
}