Topic:
Given a binary tree, returns its middle order traversal. Example: input: [1,null,2,3] 1 2 / 3 output: [1,3,2] Advanced: Recursive algorithm is very simple, can you do it by iterative algorithm?
Solving algorithm:
/** * Definition for a binary tree node. * 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) { Stack<treenode *> Mystack; vector<int> Res; if (root = NULL) { return res; } Mystack.push (root); s = root; while (!mystack.empty () &&s) { TreeNode * RootNode = Mystack.top (); while (rootnode->left) { RootNode = rootnode->left; Mystack.push (RootNode); } TreeNode * node = Mystack.pop (); Res.push_back (Node->val); } return res; }};
"Intermediate algorithm" 10. Traversing binary tree in sequence