Binary Tree Level Order Traversal
2015-03-10 15:29 李涛的技术博客 阅读(303) 评论(0) 编辑 收藏 举报Question:
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7},
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
Solution:
借助队列,层序遍历,在队列中记录这个节点是第几层的。在从队列中取节点,同层的放在一个vector中,如果新的一层的节点出现了,则把上一层的vector放入到vector的vector中。这样记录的是从上到下遍历的结果,把vector反转即可。代码如下,通过了leetcode的在线测试。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int> > levelOrderBottom(TreeNode *root) { vector<vector<int> > vecRes; if (!root) return vecRes; queue<pair<TreeNode*, int> > nodeQue; // first is val, second is layer vector<vector<int> > vecWorker; vector<int> vec; nodeQue.push(make_pair(root, 1)); int layer = 1; while (!nodeQue.empty()) { TreeNode* node = nodeQue.front().first; int nodeLayer = nodeQue.front().second; nodeQue.pop(); if (nodeLayer > layer) { vecWorker.push_back(vec); vec.clear(); layer = nodeLayer; } vec.push_back(node->val); if (node->left) { nodeQue.push(make_pair(node->left, nodeLayer+1)); } if (node->right) { nodeQue.push(make_pair(node->right, nodeLayer+1)); } } vecWorker.push_back(vec); for (int i = vecWorker.size()-1; i >= 0; i--) { vecRes.push_back(vecWorker[i]); } return vecRes; } };
时间复杂度,O(n),n是树的节点数。