[Leetcode] Binary Tree Inorder Traversal (Java)

来源:互联网 发布:微信刷票软件免费版 编辑:程序博客网 时间:2024/06/05 19:33

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?

中序遍历,递归很简单

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


0 0
原创粉丝点击