107. Binary Tree Level Order Traversal II

来源:互联网 发布:北京大兴区行知小学 编辑:程序博客网 时间:2024/06/05 10:41

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,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[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) {        vector<TreeNode*> father, son;        father.push_back(root);        vector<vector<int>> ans;        if(root == NULL) return ans;        else ans.push_back({root->val});        vector<int> tmp;        int cnt = 0;        while(1){            if(root->left != NULL){                son.push_back(root->left);                tmp.push_back(root->left->val);            }            if(root->right != NULL){                son.push_back(root->right);                tmp.push_back(root->right->val);            }            ++cnt;            if(cnt == father.size()){                father = son;                cnt = 0;                if(father.empty())                    break;                ans.push_back(tmp);                son.clear();                tmp.clear();            }            root = father[cnt];        }        reverse(ans.begin(), ans.end());        return ans;    }};
0 0