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)