Java中二叉树的前序遍历、中序遍历及后续遍历代码

公共类——节点类代码:

//  Definition for a binary tree node.
public class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
 }

一、二叉树的前序遍历

class PreOrder {
    public List<Integer> preorderTest(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        preOrder(root, res);
        return res;
    }
    public void preOrder(TreeNode root, List<Integer> res) {
        if (root == null)
            return;
        //先打印当前节点,然后打印左子树,最后再打印右子树
        res.add(root.val);
        preOrder(root.left, res);
        preOrder(root.right, res);
    }
}

二、二叉树的中序遍历

class InOrder {
    public List<Integer> inorderTest(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        inOrder(root, res);
        return res;
    }

    public void inOrder(TreeNode root, List<Integer> res) {
        if(root == null) return;
        inOrder(root.left, res);
        res.add(root.val);
        inOrder(root.right, res);
    }
}

三、二叉树的后序遍历

class PostOrder {
    public List<Integer> postorderTest(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        postOrder(root, res);
        return res;
    }

    public void postOrder(TreeNode root, List<Integer> res){
        if (root == null) return;
        postOrder(root.left, res);
        postOrder(root.right, res);
        res.add(root.val);
    }
}

 

上一篇:链表-删除链表的倒数第N个节点(双指针法)


下一篇:Java数据冒泡排序