Binary Tree inorder Traversal--leetcode

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.