首页 > 代码库 > 【Lintcode】069.Binary Tree Level Order Traversal
【Lintcode】069.Binary Tree Level Order Traversal
题目:
Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).
Example
Given binary tree {3,9,20,#,#,15,7}
,
3 / 9 20 / 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
题解:
三种处理方法:queue + queue; queue + ‘dummy’;queue
Solution 1 ()
class Solution { /** * @param root: The root of binary tree. * @return: Level order a list of lists of integer */ public: vector<vector<int>> levelOrder(TreeNode *root) { vector<vector<int>> res; if (root == NULL) { return res; } queue<TreeNode*> queue; vector<int> levelNode; queue.push(root); queue.push(nullptr); while(!queue.empty()) { TreeNode *node = queue.front(); queue.pop(); if (node == nullptr) { res.push_back(levelNode); levelNode.resize(0); if (q.size() > 0) { q.push(nullptr); } } else { levelNode.push_back(root->val); if (node->left != nullptr) { queue.push(node->left); } if (node->right != nullptr) { queue.push(node->right); } } } return res; } };
Solution 2 ()
class Solution { /** * @param root: The root of binary tree. * @return: Level order a list of lists of integer */ public: vector<vector<int>> levelOrder(TreeNode *root) { vector<vector<int>> res; if (root == NULL) { return res; } queue<TreeNode*> queue; queue.push(root); while(!queue.empty()) { int size = queue.size(); vector<int> levelNode; for (int i = 0; i < size; i++) { TreeNode *node = queue.front(); queue.pop(); levelNode.push_back(node->val); if (node->left != nullptr) { queue.push(node->left); } if (node->right != nullptr) { queue.push(node->right); } } res.push_back(levelNode); } return res; } };
程序中的size是必要的,因为在for循环中queue是不断变化的,那么queue.size()也是不断变化的,这就违背了我们的原则,这个size就是该层所有的非空node的个数,取完之后就要压入result中,读取下一层的节点
【Lintcode】069.Binary Tree Level Order Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。