最簡單的二叉樹中序遍歷題目,其實我比較好奇的輸入的「#」,如何被識別爲null。 難度係數1/5 java
Given a binary tree, return the inorder traversal of its nodes' values. node
For example:
Given binary tree{1,#,2,3}, 函數
1 \ 2 / 3
return[1,3,2]. code
代碼以下 it
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public ArrayList<Integer> inorderTraversal(TreeNode root) { // Start typing your Java solution below // DO NOT write main() function ArrayList<Integer> list = new ArrayList(); tarvel(root,list); return list; } public void tarvel(TreeNode root,ArrayList<Integer> list){ if(root == null) return ; tarvel(root.left,list); list.add(root.val); tarvel(root.right,list); } }因爲子函數返回一個ArrayList<Integer>,不是void,因此最簡單的是再本身添加一個返回void的函數