按层输出二叉树,广度优先。
3 / 9 20 / 15 7
[ [15,7], [9,20], [3] ]
/** * 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>> rres; void levelTree(TreeNode*root, int level){ if (root == NULL) return; if (level == rres.size()){ vector<int> res; rres.push_back(res); } rres[level].push_back(root->val); levelTree(root->left,level+1); levelTree(root->right,level+1); } vector<vector<int>> levelOrderBottom(TreeNode* root) { levelTree(root,0); //return reverse(rres.begin(),rres.end()); return vector<vector<int> >(rres.rbegin(), rres.rend()); } };
原文地址:https://www.cnblogs.com/sherry-yang/p/8445735.html
时间: 2024-10-24 00:59:46