[Leetcode] Binary Tree level Order traversal II

Source: Internet
Author: User

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

Related Article

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.