中序遍历迭代方法在二叉树面试总结一文中写了
package Level2;
import java.util.ArrayList;
import Utility.TreeNode;
/**
* Binary Tree Inorder Traversal
*
* 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 you do it iteratively?
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
*
*/
public class S24 {
public static void main(String[] args) {
}
public ArrayList<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> ret = new ArrayList<Integer>();
rec(root, ret);
return ret;
}
public void rec(TreeNode root, ArrayList<Integer> ret){
if(root == null){
return;
}
rec(root.left, ret);
ret.add(root.val);
rec(root.right, ret);
}
}
最优解法:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> ret = new ArrayList<Integer>();
if(root == null){
return ret;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode cur = root;
while(true){
while(cur != null){
stack.push(cur);
cur = cur.left;
}
if(stack.isEmpty()){
break;
}
cur = stack.pop();
ret.add(cur.val);
cur = cur.right;
}
return ret;
}
}
之前自己写的,可以AC,但是要改变原树结构,不好!
public static ArrayList<Integer> inorderTraversal2(TreeNode root) {
ArrayList<Integer> ret = new ArrayList<Integer>();
if(root == null){
return ret;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
TreeNode cur = stack.peek();
while(!stack.isEmpty()){
while(cur.left != null){
stack.push(cur.left);
cur = cur.left;
}
cur = stack.pop();
ret.add(cur.val);
if(cur.right != null){
cur = cur.right;
stack.push(cur);
}else{
if(stack.isEmpty()){
break;
}
cur = stack.peek();
if(cur.left!=null){
cur.left = null;
}
}
}
return ret;
}