144 Binary Tree Preorder traversal (binary trees pre-sequence traversal) + (binary tree, iteration)

Source: Internet
Author: User

translation
给定一个二叉树,返回其前序遍历的节点的值。例如:给定二叉树为 {1,#, 2, 3}   1         2    /   3返回 [123]备注:用递归是微不足道的,你可以用迭代来完成它吗?
Original
returntheofits nodes‘ values.For example:Given binary tree {1,#,2,3},   1         2    /   3return [1,2,3isit iteratively?
Analysis

The topic let me try to iterate, but the first to honestly give the recursion to write to say it ~

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<int> v;    vector<int> preorderTraversal(TreeNode* root) {        if (root != NULL) {            v.push_back(root->val);            preorderTraversal(root->left);            preorderTraversal(root->right);        }        return v;    }};

Next, let's write the iteration ...

/*** 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*>Tempstack; while(!tempstack.empty () | | root! = NULL) {if(Root = NULL)                {Result.push_back (root->val);                Tempstack.push (root);            root = root->left; }Else{root = Tempstack.top ();                Tempstack.pop ();            root = root->right; }        }returnResult }};

144 Binary Tree Preorder traversal (binary trees pre-sequence traversal) + (binary tree, iteration)

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.