Leetcode_94_binary Tree inorder Traversal

Source: Internet
Author: User

1. Description

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?

2. Ideas

A. Go through the left subtree until the left child is empty

B. Then see if the right subtree of the current node is empty, is empty, then accesses the current node, pops up the current node, re-judges it, does not empty, accesses the current node, pops the current node, and returns the right child of the current node into the stack, returning a

C. It is important to note that after the current node is ejected, it is determined whether the stack is empty before the current node at the top of the stack is obtained

3. Code

Public list<integer> inordertraversal (TreeNode root) {     list<integer>list=new Arraylist<integer > ();     if (root==null) return list;     Stack<treenode>st=new stack<treenode> ();     St.push (root);     TreeNode Top=null;     while (!st.empty ())     {     top=st.peek ();     while (Top.left!=null)     {     st.push (top.left);     Top=top.left;     }     while (Top.right==null)     {     list.add (top.val);     St.pop ();     if (!st.empty ())     Top=st.peek ();     else break     ;     }     if (!st.empty ())     {     list.add (top.val);     St.pop ();     St.push (top.right);     }          }     return list; }


4. Results


Leetcode_94_binary Tree inorder Traversal

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.