Original title Link: https://oj.leetcode.com/problems/binary-tree-inorder-traversal/
The main idea: the middle sequence traverse the binary tree
The idea of solving problems: the middle sequence traverses the binary tree, the middle sequence traverses the left subtree of the binary tree, accesses the root node, and traverses the right sub-tree of the binary tree in sequence. When a non-recursive implementation is implemented, a stack is used to simulate the traversal process. Because the left subtree needs to be traversed first, each node is first entered into the stack and accessed when it is out of the stack.
Vector<int> inordertraversal (TreeNode *root) { vector<int> ret; if (!root) return ret; stack<treenode*> s; while (root| |! S.empty ()) { if (!root) {root=s.top (); Ret.push_back (Root->val); S.pop ();root=root->right; } Else{s.push (root); root=root->left;} }
Complexity analysis: The time complexity is O (N), because each node is traversed only once. The spatial complexity is O (LgN), which is the maximum length of the stack, which is the depth of the tree.
The middle sequence traversal and the first permit traversal need to be mastered skillfully, Bug-free Oh!
Binary Tree inorder Traversal--leetcode