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