Binary Tree level Order traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes ' values. (ie, from the left-to-right, the level by level from the leaf to root).
For example:
Given binary Tree {3,9,20,#,#,15,7}
,
3 / 9 / 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.
Problem Solving Ideas:
The problem test instructions is to traverse the binary tree from bottom to top, and the result exists in a two-dimensional vector. You can find the height of the tree, determine the size of the first dimension of the two-dimensional vector, and then depth through the enumeration to insert the value into the corresponding position. The following method requires only 8ms. Another problem given in the topic: {1,#,2,3} means storing a binary tree as an array, #表示对应的节点为空, subscript can represent the relationship of two nodes.
/** * 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 (r OOT); 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)); }};
[Leetcode] Binary Tree level Order traversal II