二叉树中序遍历

二叉树中序遍历,分为递归和非递归方法:

递归:

private static List<Integer> inList = new ArrayList<>();
public static List<Integer> inorderTraversalRec(TreeNode root){
    if (null == root){
        return inList;
    }
    inorder(root);
    return inList;
}
private static void inorder(TreeNode root){
    if (null == root){
        return;
    }
    inorder(root.left);
    inList.add(root.val);
    inorder(root.right);
}

非递归:

public static List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> list = new ArrayList<>();
    if (null == root){
        return list;
    }
    Stack<TreeNode> stack = new Stack<>();
    TreeNode cur = root;
    while (null != cur || !stack.isEmpty()){
        while (null != cur){
            stack.push(cur);
            cur = cur.left;
        }
        TreeNode node = stack.pop();
        list.add(node.val);
        cur = node.right;
    }
    return list;
}
原文地址:https://www.cnblogs.com/earthhouge/p/11262916.html