leetcode刷题,总结,记录,备忘 107

来源:互联网 发布:老男孩linux运维2017 编辑:程序博客网 时间:2024/05/20 09:10

leetcode107Binary 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.

不是很难的题目,请一定学会使用队列,栈容器,十分有用。通过一个count变量记录每层节点个数,并将一层的所有节点的值域放入数组之后,将一个数组放入二维数组中去,然后清空数组,继续同样的操作,最后将二维数组反序返回即可。

/** * 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) {        if (!root) {            return vector<vector<int> >();        }        vector<vector<int> > vi;        queue<TreeNode*> st;        st.push(root);        int count = 1;        vector<int> vti;        while (!st.empty()) {            TreeNode * tempTreeNode = st.front();            st.pop();            vti.push_back(tempTreeNode->val);            if (tempTreeNode->left) {                st.push(tempTreeNode->left);            }            if (tempTreeNode->right) {                st.push(tempTreeNode->right);            }            count--;            if (count == 0) {                vi.push_back(vti);                count = st.size();                vti.clear();             }        }        return vector<vector<int> >(vi.rbegin(), vi.rend());    }};


0 0