Leetcode94——Binary Tree Inorder Traversal

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. 问题描述

Given a binary tree, return the inorder traversal of its nodes' values.

For example:
Given binary tree [1,null,2,3],

   1
    \
     2
    /
   3

return [1,3,2].

2. 求解

这个题就是一个树的中序遍历问题,最简单的方案就是递归的遍历子树,要注意递归退出的条件。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List inorderTraversal(TreeNode root) {
        List list = new ArrayList();
        if(root == null) {
            return list;
        }
        List left = inorderTraversal(root.left);
        List right = inorderTraversal(root.right);
        list.addAll(left);
        list.add(root.val);
        list.addAll(right);
        return list;
    }
}

你可能感兴趣的:(Leetcode94——Binary Tree Inorder Traversal)