剑指Offer(22)______从上往下打印二叉树

来源:互联网 发布:对称矩阵谱分解 编辑:程序博客网 时间:2024/06/05 14:42

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



class Solution {public:    vector<int> PrintFromTopToBottom(TreeNode* root) {        vector<int> ans;        vector<TreeNode*> tree;        if(root == NULL) return ans;         //鲁棒性: 判断二叉树非空        tree.push_back(root);        int index = 0;        while(index < tree.size()){            auto p = tree[index++];            ans.push_back(p->val);            if(p->left != NULL)tree.push_back(p->left);            if(p->right != NULL)tree.push_back(p->right);        }        return ans;    }};



0 0
原创粉丝点击