代码随想录算法刷题训练营day14

代码随想录算法刷题训练营day14:LeetCode(94)二叉树的中序遍历、LeetCode(144)二叉树的前序遍历、LeetCode(145)二叉树的后序遍历
LeetCode(94)二叉树的中序遍历
题目
代码随想录算法刷题训练营day14_第1张图片
代码

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

/**
 * 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 {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result=new ArrayList<>();
        inorder(root,result);
        return result;

    }
    //开始进行中序遍历
    //1、不需要有返回值,只需要往集合里面存值就可以了
    public void inorder(TreeNode root,List<Integer> result){
        if(root==null){
            return;
        }
        inorder(root.left, result);
        result.add(root.val);
        inorder(root.right, result);
    }
}

LeetCode(144)二叉树的前序遍历
题目
代码随想录算法刷题训练营day14_第2张图片
代码

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

/**
 * 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 {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result=new ArrayList<>();
        preorder(root,result);
        return result;
    }
    //前序遍历
    public void preorder(TreeNode root,List<Integer> result){
        if(root==null){
            return;//终止条件
        }
        result.add(root.val);
        preorder(root.left, result);
        preorder(root.right, result);
    }
}

LeetCode(145)二叉树的后序遍历
题目
代码随想录算法刷题训练营day14_第3张图片

代码

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

/**
 * 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 {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result=new ArrayList<>();
        postorder(root,result);
        return result;

    }
    //创建后续遍历
    public void postorder(TreeNode root,List<Integer> result){
        if(root==null){
            return;
        }
        postorder(root.left, result);
        postorder(root.right, result);
        result.add(root.val);
    }
}

你可能感兴趣的:(代码随想录算法训练营,算法,leetcode,数据结构,java,开发语言)