Leetcode Binary Tree inorder traversal

Source: Internet
Author: User

1. Topics


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. Solution 1


Class Solution {public  :      vector<int> inordertraversal (TreeNode *root) {          vector<int> path;          Stack<treenode *> St;          if (root = NULL)              return path;          TreeNode *p = root;          while (P! = NULL | |!st.empty ())          {              while (P! = null)              {                  st.push (p);                  p = p->left;              }              if (!st.empty ())              {                  p = st.top ();                  St.pop ();                  Path.push_back (p->val);                  p = p->right;              }          }          return path;      }  ;  

idea: The middle sequence traversal is the first access to the left node, then access, and then access to the right. Using a stack to assist, we put the left node of a node all in the stack, and then pop the leftmost node. Then the current variable pointer to its right node, also the right section of all the left node into the stack, and then popped out. Of course, the non-recursive way is still a bit difficult.


3. Solution 2


Class Solution {public  :      vector<int> result;      void Inorder (TreeNode *root)      {          if (root = NULL)              return;          Inorder (root->left);          Result.push_back (root->val);          Inorder (root->right);      }      Vector<int> inordertraversal (TreeNode *root) {          result.clear ();          Inorder (root);          return result;      }  

idea: Recursive version is still very simple.


http://www.waitingfy.com/archives/1622

Leetcode 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.