94. 二叉树的中序遍历

189 阅读1分钟

题目介绍

力扣94题:leetcode-cn.com/problems/bi…

image.png

image.png

分析

题目比较简单,直接利用二叉树的中序遍历,并且把遍历结果存入到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 {
    //用于存放中序遍历的结果
    List<Integer> result = new ArrayList<>();

     public List<Integer> inorderTraversal(TreeNode root) {
         inOrder(root , result);
         return result;
     }

     public void inOrder(TreeNode root , List<Integer> result) {
         if (root == null) {
             return;
         }
         inOrder(root.left,result);
         //将遍历结果存入到集合中
         result.add(root.val);
         inOrder(root.right,result);
     }
}