Leetcode_94_binary Tree inorder Traversal

Source: Internet
Author: User

Welcome to read the reference, if there are errors or questions, please leave a message to correct, thank you

94 Binary Tree Inorder Traversal


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


For example:
Given binary Tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].


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


Method One: Stack/** * Definition for binary tree * struct TreeNode {*     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */class Solution {public:    vector<int> inordertraversal (TreeNode *root) {        vector<int> ans;        Ans.clear ();        if (root==null)            return ans;        Stack<treenode *> St;        TreeNode *p = root;        while (P!=null | |!st.empty ())        {            while (p!=null)            {                st.push (p);                p = p->left;            }            if (!st.empty ())            {                p = st.top ();                St.pop ();                Ans.push_back (p->val);                p = p->right;            }        }        return ans;    };


Method Two: Recursive class solution {vector<int> ans;public:    void Inordertraversalutil (TreeNode *root)    {        if ( Root==null)            return;        Inordertraversalutil (root->left);        Ans.push_back (root->val);        Inordertraversalutil (root->right);    }        Vector<int> inordertraversal (TreeNode *root) {        ans.clear ();        if (root = NULL)            return ans;        Inordertraversalutil (root);        return ans;    };



Leetcode_94_binary Tree inorder 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.