中序遍历二叉树

二叉树中序遍历的规则:
(1)中序遍历左子树

(2)访问根节点

(3)中序遍历右子树
输入、输出描述
输入:
给定一个二叉树的根节点
输出:
返回中序遍历二叉树节点序列对应的”data"属性列表
Example
输入:
二叉树如下:
    1
   / \
   2  3
  /  / \
  4  5  6
输出:
4,2,1,5,3,6
代码:
import java.util.*;

public class Main {

     public Integer[] solution(TreeNode<Integer> data) {
        List<Integer> result = new ArrayList<>();
        solution(data, result);
        return result.toArray(new Integer[result.size()]);
    }

    void solution(TreeNode<Integer> data, List<Integer> result) {
        if (data == null) {
            return;
        }
        solution(data.left, result);
        result.add(data.data);
        solution(data.right, result);
    }
}
一个创业中的苦逼程序员
评论专区

隐藏