美文网首页
144. 二叉树的前序遍历、94. 二叉树的中序遍历、145.

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

作者: Abeants | 来源:发表于2021-10-22 11:33 被阅读0次

    不多逼逼,直接上码:
    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);
        }
    }
    

    相关文章

      网友评论

          本文标题:144. 二叉树的前序遍历、94. 二叉树的中序遍历、145.

          本文链接:https://www.haomeiwen.com/subject/jvvcaltx.html