[Leetcode] Middle sequence traversal of binary tree inorder traversal two

Source: Internet
Author: User

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?

Confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

The sequence traversal order of binary tree is left-root-right, which can be solved by both recursive and non-recursive methods. We first look at the recursive method, very direct, to the left Dial hand node call recursive function, the root node access value, the right child node and then call the recursive function, the code is as follows:

//recursionclassSolution { Public: Vector<int> Inordertraversal (TreeNode *root) {Vector<int>Res;        Inorder (Root, res); returnRes; }    voidInorder (TreeNode *root, vector<int> &Res) {        if(!root)return; if(root->left) inorder (root->Left , RES); Res.push_back (Root-val); if(root->right) inorder (root->Right , res); }};

Next we look at the non-recursive solution, but also the problem requires the use of the solution, need to do with the stack, the idea is to start from the root node, the root node is pressed into the stack, and then all of its left dial hand nodes are pressed into the stack, and then the top node of the stack, save the node value, and then move the current pointer The next cycle, all of its left dial hand nodes can be pressed into the stack. This ensures that the access order is left-root-right and the code is as follows:

//non-recursionclassSolution { Public: Vector<int> Inordertraversal (TreeNode *root) {Vector<int>Res; Stack<TreeNode*>s; TreeNode*p =Root;  while(P | |!S.empty ()) {             while(P) {S.push (P); P= p->Left ; } P=S.top ();            S.pop (); Res.push_back (P-val); P= p->Right ; }        returnRes; }};

[Leetcode] Middle sequence traversal of binary tree inorder traversal two

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.