[LeetCode] Binary Tree Inorder Traversal

Source: Internet
Author: User
Question:

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, cocould you do it iteratively?


Ideas:

The non-recursive middle-order traversal of a binary tree is similar to that of a forward-order traversal. Just change the location of the access value.


Code: C ++:

/*** 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; stack <TreeNode *> s; TreeNode * p = root; while (p! = NULL |! S. empty () {while (p! = NULL) {s. push (p); p = p-> left;} if (! S. empty () {p = s. top (); s. pop (); ans. push_back (p-> val); p = p-> right ;}} return ans ;}};

Python: (writing stacks with Python is amazing)

# Definition for a binary tree node # class TreeNode: # def _ init _ (self, x): # self. val = x # self. left = None # self. right = Noneclass Solution: # @ param root, a tree node # @ return a list of integers def inorderTraversal (self, root): ans = [] s = [] while root! = None or s: while root! = None: s. append (root) root = root. left if s: root = s [-1] s. pop () ans. append (root. val) root = root. right return ans

[LeetCode] 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.