二叉树中序遍历:左-中-右
树节点
class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int val) {
this.val = val;
this.left = this.right = null;
}
}
递归实现
/*
* 二叉树中序遍历
* 递归实现
*/
public class InorderTraversal {
public ArrayList<Integer> inorderTraversal(TreeNode root)
{
ArrayList<Integer> arr = new ArrayList<Integer>();
inorder(arr,root);
return arr;
}
public ArrayList<Integer> inorder(ArrayList<Integer> arr, TreeNode root)
{
if(root == null)
return arr;
if(root!=null)
{
if(root.left!=null)
{
arr = inorder(arr, root.left);
}
arr.add(root.val);
if(root.right!=null)
{
arr = inorder(arr, root.right);
}
}
return arr;
}
}
/*
* 二叉树中序遍历
* 非递归方式
*/
public class InorderTraversal1 {
public ArrayList<Integer> inorderTraversal(TreeNode root)
{
ArrayList<Integer> arr = new ArrayList<Integer>();
ArrayList<TreeNode> p =new ArrayList<TreeNode>();
if(root == null)
{
return arr;
}
while(root!=null || p.size()!=0)
{
while(root!=null)
{
p.add(root);
root = root.left;
}
root = p.get(p.size()-1);
arr.add(root.val);
p.remove(p.size()-1);
root = root.right;
}
return arr;
}
}