Topic:
Given a binary tree, return the inorder traversal of its nodes ' values.
For example:
Given binary Tree {1,#,2,3},
1 2 /
return [1,3,2].
Note:recursive solution is trivial, could do it iteratively?
Recursive solution (c + +):
/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL), right (N ULL) {} *}; */ class solution{private : vector <int > result; public : vector <int ; inordertraversal (TreeNode *root) {if (Root) {inordertraversal (root->left); Result.push_back (Root->val); Inordertraversal (Root->right); } return result; }};
The non-recursive algorithm of sequential traversal in binary tree and the idea of pre-order traversal are mostly solved by using the stack structure, referring to Leetcode:binary tree preorder traversal (binary trees pre-sequence traversal).
Non-recursive solution (c + +):
classsolution{ Public: vector<int>Inordertraversal (TreeNode *root) { vector<int>Result Stack<TreeNode*>Nodes TreeNode *node = root; while(Node | |!nodes.empty ()) {if(node) {Nodes.push (node); node = node->left; }Else{node = Nodes.top (); Result.push_back (Node->val); Nodes.pop (); node = node->right; } }returnResult }};
C # Non-recursive solution:
/** * Definition for Binary tree * public class TreeNode {* public int val; * Public TreeNode left; * Pub Lic TreeNode right; * Public TreeNode (int x) {val = x;} *} */ Public class solution{ Publicilist<int>Inordertraversal(TreeNode Root) {ilist<int> result =Newlist<int> (); stack<treenode> nodes =NewStack<treenode> (); TreeNode node = root;//When result or nodes is not empty while(Node! =NULL|| Nodes. Count >0) {//node not empty time has been walking along the Zuozi, along the way node into the stack if(Node! =NULL) {nodes. Push (node); node = Node.left; }when//node empty, it means finding the leftmost subtree. Else{//stack top element pops into resultnode = nodes. Pop (); Result. ADD (Node.val);//node points to the right subtree of the node, continuing the loopnode = node.right; } }returnResult }}
Leetcode:binary Tree inorder Traversal (binary tree sequence traversal)