Java 实现 二叉树的 后序遍历

发布时间 2023-05-03 04:44:19作者: 龙凌云端

Java 实现 二叉树的 后序遍历


 

class Node {
    int val;
    Node left;
    Node right;
    
    public Node(int val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

public class PostorderTraversal {
    public static void postorderTraversal(Node root) {
        if (root != null) {
            postorderTraversal(root.left);
            postorderTraversal(root.right);
            System.out.print(root.val + " ");
        }
    }
    
    public static void main(String[] args) {
        // 构建二叉树
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);
        
        // 后序遍历
        System.out.print("Postorder Traversal: ");
        postorderTraversal(root);
    }
}