バイナリ ツリーの順序トラバーサル - 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