首页 > 代码库 > LeetCode:Binary Tree Level Order Traversal II
LeetCode:Binary Tree Level Order Traversal II
本题和上题一样同属于层次遍历,不同的是本题从底层往上遍历,如下:
代码如下:
1 struct TreeNode { 2 int val; 3 TreeNode* left; 4 TreeNode* right; 5 TreeNode():val(0),left(NULL),right(NULL){} 6 TreeNode(int x): val(x), left(NULL),right(NULL) {} 7 }; 8 9 vector<vector<int> > levelOrderTraversalII(TreeNode *root) //非递归的中序遍历(用栈实现)10 {11 12 queue<TreeNode *> tree_queue;13 vector<vector<int> > tree_vector, tree_rvector;14 vector<int> svector;15 int nCount = 0;16 17 if (NULL == root) {18 return tree_vector;19 }20 TreeNode *pTemp = root;21 tree_queue.push(root);22 tree_queue.push(NULL); //the end of one level.23 24 while (true) {25 TreeNode *pTemp = tree_queue.front();26 tree_queue.pop();27 28 if (!pTemp) { //get the null, put vector<> to vector<vector<>>29 tree_vector.push_back(svector);30 nCount ++;31 svector.clear();32 if (tree_queue.empty())33 break;34 tree_queue.push(NULL);35 }36 else {37 svector.push_back(pTemp->val);38 if (pTemp->left) 39 tree_queue.push(pTemp->left);40 if (pTemp->right)41 tree_queue.push(pTemp->right);42 }43 }44 while (nCount > 0){45 svector = tree_vector.at(nCount - 1);46 tree_rvector.push_back(svector);47 nCount --;48 }49 return tree_rvector;50 }
LeetCode:Binary Tree Level Order Traversal II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。