Leetcode: Binary Tree preorder traversal

Source: Internet
Author: User

Title: Binary Tree preorder traversal

The stack is also used for the forward traversal of a binary tree. The Code is as follows:

 1 struct TreeNode { 2     int            val; 3     TreeNode*    left; 4     TreeNode*    right; 5     TreeNode(int x): val(x), left(NULL),right(NULL) {} 6 }; 7  8 vector<int> preorderTraversal(TreeNode *root) //非递归的前序遍历(用栈实现) 9 {10     if (NULL == root) {11         cout << "tree is empty!" << endl;12         exit(0);13     }14 15     TreeNode *pre = root;16     //TreeNode *pTemp = pre;17     stack<TreeNode *> tree_stack;18     vector<int> tree_vector;19     20     tree_stack.push(pre);21     while (!tree_stack.empty()) {22         TreeNode *pTemp = tree_stack.top();23         tree_stack.pop();24 25         tree_vector.push_back(pTemp->val);26         if (pTemp->right != NULL) 27             tree_stack.push(pTemp->right);28         if (pTemp->left != NULL)29             tree_stack.push(pTemp->left);30     }31     return tree_vector;32 }

 

Leetcode: Binary Tree preorder traversal

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.