"Leetcode" 144. Binary Tree Preorder Traversal

Source: Internet
Author: User

Title:

Given a binary tree, return the preorder traversal of its nodes ' values.

For example:
Given binary Tree {1,#,2,3} ,

   1         2    /   3

Return [1,2,3] .

Note: Recursive solution is trivial, could do it iteratively?

Tips:

First, you need to clear the order of the pre-order traversal, that is, the left child-to-right child, node, which is traversed in this order.

A more flattering approach to this problem is to declare a vector member variable in the solution class so that you can push the element through the vector in a recursive way. However, if the requirement must be solved only by the given function, then you need to use the "stack" data structure to simulate the recursive invocation of the function, the method can refer to the implementation of the Code.

Code:
/** Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right ; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: Vector<int> Preordertraversal (treenode*root) {Vector<int>result; Stack<TreeNode*>Node_stack;        Node_stack.push (root);  while(!Node_stack.empty ()) {TreeNode*node =Node_stack.top ();            Node_stack.pop (); if(node = =NULL) {                Continue; } Result.push_back (Node-val); Node_stack.push (Node-Right ); Node_stack.push (Node-Left ); }        returnresult; }};

"Leetcode" 144. 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.