给出一棵二叉树,返回其中序遍历
样例
给出二叉树 {1,#,2,3},
1
\
2
/
3
返回 [1,3,2].
代码
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import LintClass.TreeNode;
/**
* 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 InorderTraversal_67 {
/*
* @param root: A Tree
* @return: Inorder in ArrayList which contains node values.
*/
List<Integer> output = new ArrayList<Integer>();
public List<Integer> inorderTraversal(TreeNode root) {
// left, root, right
TreeNode cur = root;
if(cur == null)
return output;
if(cur.left != null) {
inorderTraversal(cur.left);
}
output.add(cur.val);
if(cur.right != null) {
inorderTraversal(cur.right);
}
return output;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode root_1_right = new TreeNode(2);
TreeNode root_2_left = new TreeNode(3);
root.right = root_1_right;
root.right.left = root_2_left;
InorderTraversal_67 obj = new InorderTraversal_67();
System.out.print(obj.inorderTraversal(root));
}
}
网友评论