[LeetCode][Java] Binary Tree Inorder Traversal

来源:互联网 发布:淘宝人工服务号码多少 编辑:程序博客网 时间:2024/06/09 20:57

题目:

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

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

题意:

二叉树的中序遍历,就是左-中-右。

算法分析:

由于二叉树的特殊的重复结构,递归是最易想到,也是最好理解的做法。

代码如下:

 //递归public class Solution {static ArrayList<Integer> res= new ArrayList<Integer>();    public  ArrayList<Integer> inorderTraversal(TreeNode root)     {          res.clear();    inorder( root);return res;}private static void inorder(TreeNode root) {    if (root == null)              return;inorder(root.left);res.add(root.val);inorder(root.right);}}


0 0
原创粉丝点击