144. 二叉树的前序遍历、94. 二叉树的中序遍历、145. 二叉树的后序遍历

不多逼逼,直接上码:
144. 二叉树的前序遍历

/**
 * 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 Solution {
    List res = new ArrayList<>();

    public List preorderTraversal(TreeNode root) {
        getPreorder(root);

        return res;
    }

    public void getPreorder(TreeNode root) {
        if (root == null) return;
        res.add(root.val);
        getPreorder(root.left);
        getPreorder(root.right);
    }
}

94. 二叉树的中序遍历

/**
 * 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 Solution {
    List res = new ArrayList<>();

    public List inorderTraversal(TreeNode root) {
        getInorder(root);

        return res;
    }

    public void getInorder(TreeNode root) {
        if (root == null) return;
        getInorder(root.left);
        res.add(root.val);
        getInorder(root.right);
    }
}

145. 二叉树的后序遍历

/**
 * 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 Solution {
    List res = new ArrayList<>();

    public List postorderTraversal(TreeNode root) {
        getpostorder(root);
        
        return res;
    }

    public void getpostorder(TreeNode root) {
        if (root == null) return;
        getpostorder(root.left);
        getpostorder(root.right);
        res.add(root.val);
    }
}

你可能感兴趣的:(144. 二叉树的前序遍历、94. 二叉树的中序遍历、145. 二叉树的后序遍历)