The "Sword refers to offer" prints a binary tree in the alphabetic order. The sword refers to offer rebuilding a binary tree.

Source: Internet
Author: User

The "Sword refers to offer" prints a binary tree in the alphabetic order. The sword refers to offer rebuilding a binary tree.

[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]


Question link: http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0? Rp = 3 & ru =/ta/coding-interviews & qru =/ta/coding-interviews/question-ranking


Description
Please implement a function to print a binary tree in the font, that is, the first line is printed from left to right, and the second layer is printed from right to left, the third row is printed from left to right, and the other rows are printed accordingly.


Ideas
It is the same as printing a binary tree into multiple rows. Here we only need to add a number to calculate the number of rows.

/*struct TreeNode {    int val;    struct TreeNode *left;    struct TreeNode *right;    TreeNode(int x) :            val(x), left(NULL), right(NULL) {    }};*/class Solution{public:vector<vector<int> > Print(TreeNode* pRoot){vector<vector<int> > ans;vector<int> path;if(pRoot==nullptr)return ans;int cnt = 0;queue<TreeNode*> Q,tmp;Q.push(pRoot);while(!Q.empty()){while(!Q.empty()){TreeNode *pNode = Q.front();path.push_back(pNode->val);Q.pop();if(pNode->left)tmp.push(pNode->left);if(pNode->right)tmp.push(pNode->right);}if(cnt%2)reverse(path.begin(),path.end());cnt++;ans.push_back(path);path.clear();while(!tmp.empty()){Q.push(tmp.front());tmp.pop();}}return ans;}};


Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source

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.