Tree

import java.io.*; import java.util.*; class myCode { public static void main (String[] args) throws java.lang.Exception { System.out.println("Hello Java"); TreeNode node1 = new TreeNode(5); TreeNode node2 = new TreeNode(3); TreeNode node3 = new TreeNode(8); TreeNode node4 = new TreeNode(1); TreeNode node5 = new TreeNode(4); TreeNode node6 = new TreeNode(11); node1.left = node2; node1.right = node3; node2.left = node4; node2.right = node5; node3.right = node6; Solution test = new Solution(); List<Integer> result = new ArrayList<Integer>(); result = test.preOrder(node1); //System.out.println(result); for (Integer number : result) { System.out.println(number); } } } class Solution { public List<Integer> preOrder(TreeNode root) { List<Integer> preorder = new ArrayList<Integer>(); if (root == null) { return preorder; } preorder.add(root.key); if (root.left != null) { preorder.addAll(preOrder(root.left)); } if (root.right != null) { preorder.addAll(preOrder(root.right)); } return preorder; } } class TreeNode { public int key; public TreeNode left; public TreeNode right; public TreeNode (int key) { this.key = key; } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.