"Sword refers to offer" prints a binary tree from top down, and the sword refers to offer rebuilding a binary tree.

Source: Internet
Author: User

"Sword refers to offer" prints a binary tree from top down, and 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/7fe2212963db4790b57431d9ed259701? Rp = 2 & ru =/ta/coding-interviews & qru =/ta/coding-interviews/question-ranking


Description
Each node of the binary tree is printed from top to bottom, and the nodes at the same layer are printed from left to right.

Ideas
This is an obvious search question with a high degree of breadth. Starting from the root node, we first store its subnodes in the queue in the left-to-right order, according to the features of the first-in-first-out queue, each time the nodes in the pop-up queue arrive at the next layer after processing the same layer, this meets the requirements of the question.


/*struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}};*/class Solution{public:vector<int> PrintFromTopToBottom(TreeNode *root){vector<int> ans;if(root==nullptr) return ans;queue<TreeNode*> Q;Q.push(root);while(!Q.empty()){TreeNode *now = Q.front();Q.pop();ans.push_back(now->val);if(now->left)Q.push(now->left);if(now->right)Q.push(now->right);}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.