首页 > 代码库 > Problem Binary Tree Preorder Traversal

Problem Binary Tree Preorder Traversal

Problem  Description:

Given a binary tree, return the preorder traversal of its nodes‘ values.

 Solution:

 1     public List<Integer> preorderTraversal(TreeNode root) { 2         if (root == null) return new LinkedList<Integer>(); 3         List<Integer> list = new LinkedList<Integer>(); 4         if (root.left == null && root.right == null) { 5             List<Integer> leaf = new LinkedList<Integer>(); 6             leaf.add(root.val); 7             return leaf; 8         }  9         list.add(root.val);10         if (root.left != null) list.addAll(preorderTraversal(root.left));11         if (root.right != null) list.addAll(preorderTraversal(root.right));12         13         return list;14     }