赞
踩
// 二叉树结构体
struct TreeNode {
TreeNode() : m_val(0), m_left_node(NULL), m_right_node(NULL) { }
TreeNode(int val) : m_val(val), m_left_node(NULL), m_right_node(NULL) { }
TreeNode(int val, TreeNode* left_node, TreeNode* right_node) : m_val(val), m_left_node(left_node), m_right_node(right_node) { }
int m_val;
TreeNode* m_left_node;
TreeNode* m_right_node;
};
class Solution { public: std::vector<std::vector<int>> Traversal(TreeNode* root) { std::vector<std::vector<int>> result; if (!root) return result; std::queue<TreeNode*> queue; queue.push(root); while (!queue.empty()) { int queue_size = queue.size(); std::vector<int> tmp_vector; for (int i = 0; i < queue_size; ++i) { TreeNode* tmp = queue.front(); queue.pop(); tmp_vector.push_back(tmp->m_val); if (tmp->m_left_node) queue.push(tmp->m_left_node); if (tmp->m_right_node) queue.push(tmp->m_right_node); } result.push_back(tmp_vector); } return result; } // 释放资源 void FreeSpace(TreeNode* root) { if (!root) return; if (root->m_left_node) FreeSpace(root->m_left_node); if (root->m_right_node) FreeSpace(root->m_right_node); delete root; } };
/* 给你二叉树的根节点 root ,返回它节点值的层序遍历。 */ #include <iostream> #include <vector> #include <algorithm> #include <queue> // 二叉树结构体 struct TreeNode { TreeNode() : m_val(0), m_left_node(NULL), m_right_node(NULL) { } TreeNode(int val) : m_val(val), m_left_node(NULL), m_right_node(NULL) { } TreeNode(int val, TreeNode* left_node, TreeNode* right_node) : m_val(val), m_left_node(left_node), m_right_node(right_node) { } int m_val; TreeNode* m_left_node; TreeNode* m_right_node; }; class Solution { public: std::vector<std::vector<int>> Traversal(TreeNode* root) { std::vector<std::vector<int>> result; if (!root) return result; std::queue<TreeNode*> queue; queue.push(root); while (!queue.empty()) { int queue_size = queue.size(); std::vector<int> tmp_vector; for (int i = 0; i < queue_size; ++i) { TreeNode* tmp = queue.front(); queue.pop(); tmp_vector.push_back(tmp->m_val); if (tmp->m_left_node) queue.push(tmp->m_left_node); if (tmp->m_right_node) queue.push(tmp->m_right_node); } result.push_back(tmp_vector); } return result; } // 释放资源 void FreeSpace(TreeNode* root) { if (!root) return; if (root->m_left_node) FreeSpace(root->m_left_node); if (root->m_right_node) FreeSpace(root->m_right_node); delete root; } }; int main() { // 定义一棵树 TreeNode* root = new TreeNode(5, new TreeNode(6, new TreeNode(8), NULL), new TreeNode(7, NULL, new TreeNode(9))); Solution solution; std::vector<std::vector<int>> result = solution.Traversal(root); for (int i = 0; i < result.size(); ++i) { for (int j = 0; j < result[i].size(); ++j) std::cout << result[i][j] << " "; } std::cout << std::endl; // 释放资源 solution.FreeSpace(root); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。