二叉树的中序遍历-递归与非递归实现Java

二叉树的中序遍历是一种常见的树遍历方式,按照左子树、根节点、右子树的顺序遍历二叉树节点。下面是java中二叉树中序遍历的递归和非递归实现。

import java.util.Stack;

public class test {
    static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x){
            val = x;
        }
    }

    public static void inorderTraversal(TreeNode root){
        if(root==null){
            return ;
        }

        inorderTraversal(root.left);
        System.out.println(root.val);
        inorderTraversal(root.right);
    }

    public static void inorderTraversal2(TreeNode root){
        Stack<TreeNode> stack = new Stack<>();
        TreeNode current = root;

        while (current!=null || !stack.isEmpty()){
            while (current != null){
                stack.push(current);
                current = current.left;
            }

            current = stack.pop();
            System.out.println(current.val);
            current = current.right;

        }

    }


    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);

        inorderTraversal(root);

        inorderTraversal2(root);

    }

}

猜你喜欢

转载自blog.csdn.net/qq_51118755/article/details/132795024