LeetCode94 binarytreeinordertraversal Java (recursive iteration)

Source: Internet
Author: User

Topic:

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

Solving:

In order to traverse a binary tree, if it is recursive is very simple, the middle sequence traversal left + access to the root node + sequence traversal right. iteration, I was through a stack, starting from the root node into the stack, as long as the left node has been in the stack, there is no left node on the stack to access the node value, and then continue to walk out of the stack node right node.

Code:

1, recursive

public static list<integer> result=new arraylist<> ();  public static list<integer> inordertraversal (TreeNode root,list<integer> result) {  if (root!=null)  {  inordertraversal (root.left,result);  Result.add (root.val);  Inordertraversal (Root.right,result);  }    return result;              }  
2, iteration (the following two functions are just a different notation)

public static list<integer> InorderTraversal2 (TreeNode root,list<integer> result) {  List<integer > Res=new arraylist<> ();  Stack<treenode> nodestack=new stack<> ();     while (root!=null| |! Nodestack.isempty ())  {  while (root!=null)  {  nodestack.push (root);  Root=root.left;  }    TreeNode Tempnode=nodestack.pop ();  Res.add (tempnode.val);  root=tempnode.right;    }  return res;                }    public static list<integer> InorderTraversal3 (TreeNode root,list<integer> result) {  List<integer > Res=new arraylist<> ();  Stack<treenode> nodestack=new stack<> ();    while (true) {while (root!=null) {nodestack.add (root); root=root.left;}  if (Nodestack.isempty ()) break;  TreeNode Tempnode=nodestack.pop (); Res.add (Tempnode.val); Root=tempnode.right; }  return res;                



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

LeetCode94 binarytreeinordertraversal Java (recursive iteration)

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.