算法: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;
    }
}

 一个代码里面同时实现二叉树的前序、中序、后序遍历:

算法:Java构建二叉树并递归实现二叉树的前序、中序、后序遍历_第1张图片以该二叉树为例

import java.util.ArrayList;
import java.util.List;


class PreorderTraversalSolution {

    public static void main(String[] args) {
        //构建二叉树
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.right = new TreeNode(6);
        Solution sol = new Solution();
        // 前序、中序、后序
        System.out.println(sol.preorderTraversal(root).toString());  //[1, 2, 4, 5, 3, 6]
        System.out.println(sol.inorderTraversal(root).toString());  //[4, 2, 5, 1, 3, 6]
        System.out.println(sol.postorderTraversal(root).toString());  //[4, 5, 2, 6, 3, 1]
    }
}


class Solution {
    //前序遍历
    public List preorderTraversal(TreeNode root) {
        List res = new ArrayList();
        preorder(root, res);
        return res;
    }
    public void preorder(TreeNode root, List res) {
        if (root == null) {
            return;
        }
        res.add(root.val);
        preorder(root.left, res);
        preorder(root.right, res);
    }
    //中序遍历
    public List inorderTraversal(TreeNode root) {
        List res = new ArrayList();
        inorder(root, res);
        return res;
    }
    public void inorder(TreeNode root, List res) {
        if (root == null) {
            return;
        }
        inorder(root.left, res);
        res.add(root.val);
        inorder(root.right, res);
    }
    //后序遍历
    public List postorderTraversal(TreeNode root) {
        List res = new ArrayList();
        postorder(root, res);
        return res;
    }
    public void postorder(TreeNode root, List res) {
        if (root == null) {
            return;
        }
        postorder(root.left, res);
        postorder(root.right, res);
        res.add(root.val);
    }
}

你可能感兴趣的:(数据结构与算法,leetcode&牛客,Java精修,java,算法,二叉树,前序遍历,中序遍历,后序遍历,递归)