您的位置:首页 > 其它

LeetCode——Binary Tree Inorder Traversal

2014-11-18 19:58 405 查看


Binary Tree Inorder Traversal

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?

Java代码:

/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List list = new LinkedList<Integer>();
if (root == null)
return list;
if(root.left==null && root.right==null){
list.add(root.val);
return list;
}
if (root.left == null || root.right == null) {
if (root.left == null) {
list = inorderTraversal(root.right);
list.add(0, root.val);
} else {
list.add(0, root.val);
list.addAll(0,inorderTraversal(root.left));
}
} else {
list = inorderTraversal(root.right);
list.add(0,root.val);
list.addAll(0,inorderTraversal(root.left));

}
return list;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: