04
05/2015
[LeetCode] Binary Tree Level Order Traversal II
Binary Tree Level Order Traversal II
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] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
解题思路:
这道题题意是从下往上逐层遍历二叉树,将结果存在一个二维向量中。可以先求出该树的高度,确定二维向量第一维的大小,然后深度遍历数,将值插入到相应的位置中即可。下面的方法只需8ms。另外题目中给出的问题:{1,#,2,3}表示按数组的形式存储二叉树,#表示对应的节点为空,下标能够表示两个节点的相互关系。
/** * Definition for a binary tree node. * 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) { int h = getHeight(root); vector<vector<int>> result(h, vector<int>()); traversal(root, 1, h, result); return result; } private: void traversal(TreeNode* root, int level, int h, vector<vector<int>>& result){ if(root!=NULL){ result[h-level].push_back(root->val); traversal(root->left, level+1, h, result); traversal(root->right, level+1, h, result); } } int getHeight(TreeNode* root){ if(root==NULL){ return 0; } return 1+max(getHeight(root->left), getHeight(root->right)); } };
二次刷题(2015-08-03)
/** * Definition for a binary tree node. * 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>> result; if(root==NULL){ return result; } queue<TreeNode*> q[2]; int k = 0; q[0].push(root); while(!q[k].empty()){ vector<int> item; while(!q[k].empty()){ TreeNode* node = q[k].front(); q[k].pop(); item.push_back(node->val); if(node->left!=NULL){ q[(k+1)%2].push(node->left); } if(node->right!=NULL){ q[(k+1)%2].push(node->right); } } k = (k+1)%2; result.insert(result.begin(), item); } return result; } };
0 条评论