Binary Tree level order traversal II Binary Tree sequence traversal II

Source: Internet
Author: User

Given a binary tree, returnBottom-up level orderTraversal 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:

[  [15,7],  [9,20],  [3]]

In fact, the bottom sequence traversal still starts from the top, but the storage method has changed. For more information, see my previous blog http://www.cnblogs.com/grandyang/p/4051321.html. The Code is as follows:

 

/** * 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<vector<int> > levelOrderBottom(TreeNode *root) {        vector<vector<int> > res;        if (root == NULL) return res;        queue<TreeNode*> q;        q.push(root);        while (!q.empty()) {            vector<int> oneLevel;            int size = q.size();            for (int i = 0; i < size; ++i) {                TreeNode *node = q.front();                q.pop();                oneLevel.push_back(node->val);                if (node->left) q.push(node->left);                if (node->right) q.push(node->right);            }            res.insert(res.begin(), oneLevel);        }        return res;    }};

 

Binary Tree level order traversal II Binary Tree sequence traversal II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.