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