LintCode-67.二叉树的中序遍历

题目

描述

给出一棵二叉树,返回其中序遍历

样例

给出二叉树 {1,#,2,3},

   1
    \
     2
    /
   3

返回 [1,3,2].

解答

思路

中序遍历二叉树

代码

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Inorder in ArrayList which contains node values.
     */
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        // write your code here
         ArrayList<Integer> a = new ArrayList<Integer>();
        inOrder(a, root);
        return a;
    }
    
    private void inOrder(ArrayList<Integer> a, TreeNode root){
        if(root == null) return;
        inOrder(a, root.left);
        a.add(root.val);
        inOrder(a, root.right);
    }
}
    原文作者:悠扬前奏
    原文地址: https://www.jianshu.com/p/0bdd5293d899
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞