Interview question 21: print a binary tree from top to bottom

Source: Internet
Author: User

# Include "stdafx. h "# include <iostream >#include <deque> using namespace std; struct BinaryTreeNode {int m_nValue; BinaryTreeNode * m_pLeft; BinaryTreeNode * m_pRight;}; void encode (BinaryTreeNode * pRoot) {if (pRoot = NULL) {return;} deque <BinaryTreeNode *> myDeque; myDeque. push_back (pRoot); while (! MyDeque. empty () {BinaryTreeNode * pTop = myDeque. front (); cout <pTop-> m_nValue <""; myDeque. pop_front (); if (pTop-> m_pLeft! = NULL) {myDeque. push_back (pTop-> m_pLeft);} if (pTop-> m_pRight! = NULL) {myDeque. push_back (pTop-> m_pRight) ;}}// construct a binary tree in the First Order. Input-1 indicates that the node is empty void CreateBinaryTree (BinaryTreeNode * & pRoot) {int nNodeValue = 0; cin> nNodeValue; if (-1 = nNodeValue) {return;} else {pRoot = new BinaryTreeNode (); pRoot-> m_nValue = nNodeValue; createBinaryTree (pRoot-> m_pLeft); CreateBinaryTree (pRoot-> m_pRight) ;}} void PrintInOrder (BinaryTreeNode * & pRoot) {if (pRoot! = NULL) {PrintInOrder (pRoot-> m_pLeft); cout <pRoot-> m_nValue <""; PrintInOrder (pRoot-> m_pRight );}} int _ tmain (int argc, _ TCHAR * argv []) {BinaryTreeNode * pRoot = NULL; CreateBinaryTree (pRoot); PrintInOrder (pRoot); cout <endl; printFromTopToDown (pRoot); cout <endl; system ("pause"); return 0 ;}

 

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.