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

2021-10-22  本文已影响0人  Abeants

不多逼逼,直接上码:
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<Integer> res = new ArrayList<>();

    public List<Integer> 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<Integer> res = new ArrayList<>();

    public List<Integer> 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<Integer> res = new ArrayList<>();

    public List<Integer> 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);
    }
}
上一篇下一篇

猜你喜欢

热点阅读