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],] 先查看有几层,然后填进去。
/** * 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> re; int levv; vector > levelOrderBottom(TreeNode *root) { if(root == NULL)return re; levv = level(root); for(int i = 0 ; i < levv ;i++) { vector vec; re.push_back(vec); } bottom(root,1); return re; } void bottom(TreeNode * root ,int lev) { if(root == NULL)return; re[levv - lev].push_back(root->val); bottom(root->left,lev+1); bottom(root->right,lev+1); } int level(TreeNode *root) { if(root->left == NULL && root ->right == NULL)return 1; else if(root->left == NULL) return level(root->right)+1; else if(root->right == NULL) return level(root->left)+1; else return max(level(root->left),level(root->right))+1; }};