标签:node right TreeNode nums int 构建 二叉树 数组 left
// """ // 给定一个非空列表,一层一层的构建一个二叉树。 // 例如: // input=[5,7,9,2,4,6,3,1,8,10] // 我希望返回结果: // 5(0) // / \ // 7(1) 9(2) // / \ / \ // 2(3) 4(4) 6(5) 3(6) // / \ / // 1(7) 8(8) 10(9) // 请输出这个树每个节点和其子节点的值,以便我们确定这个树的构建是正确的。 // class TreeNode(object): // def __init__(self, x): // self.val = x // self.left = None // self.right = None // #生成一个根结点,作为树的起始节点 // root=TreeNode(-1) // """ #include <iostream> #include <vector> #include <queue> #include <memory> using namespace std; class TreeNode{ public: TreeNode(int val):val_(val) {}; TreeNode* left = nullptr; TreeNode* right = nullptr; int val_ = 0; }; TreeNode* build(const vector<int>& nums,int index) { int n = nums.size(); int left = 2 * index + 1; int right = 2 * index + 2; TreeNode* node = new TreeNode(nums[index]); if(left > n - 1)node->left = nullptr; else node->left = build(nums,left); if(right > n - 1)node->right = nullptr; else node->right = build(nums,right); return node; } vector<vector<int>>levelOrder(TreeNode* root) { vector<vector<int>>res; if(nullptr == root)return res; queue<TreeNode*>q; q.push(root); while(!q.empty()) { int size = q.size(); vector<int>tmp; for(int i = 0; i < size; ++i) { TreeNode* cur = q.front(); q.pop(); tmp.push_back(cur->val_); if(cur->left)q.push(cur->left); if(cur->right)q.push(cur->right); } res.push_back(tmp); } return res; } int main() { vector<int>nums{5,7,9,2,4,6,3,1,8,10}; TreeNode* node = build(nums,0); auto res = levelOrder(node); for(auto nums:res) { for(auto num : nums) { cout << num <<" "; } cout << endl; } return 0; }
标签:node,right,TreeNode,nums,int,构建,二叉树,数组,left 来源: https://www.cnblogs.com/fourmi/p/16587032.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。