1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
| class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> ans = new LinkedList<>(); if(root != null) { preorder(ans, root); return ans; }
return ans;
}
private void preorder ( List<Integer> ans, TreeNode next) {
TreeNode node = next; ans.add(node.val);
if ( node.left == null && node.right == null) { return; }else{ if(node.left != null) { preorder(ans, node.left); } if(node.right != null) { preorder(ans, node.right); } } } }
class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> ans = new LinkedList<>();
if (root != null){ inorder(ans, root); }
return ans; }
private void inorder (List<Integer> ans, TreeNode next) { TreeNode node = next; if (node.left == null){ ans.add(node.val);
if (node.right != null) { inorder(ans, node.right); }else{ return; } }else{ inorder(ans, node.left); ans.add(node.val); if (node.right != null) { inorder(ans, node.right); } } } }
class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> ans = new LinkedList<>();
if (root != null){ postorder(ans, root); }
return ans; }
private void postorder(List<Integer> ans, TreeNode next) { TreeNode node = next;
if (node.left == null && node.right == null) { ans.add(node.val); return; }else if (node.left != null && node.right != null){ postorder(ans, node.left); postorder(ans, node.right); ans.add(node.val); }else { if ( node.left != null) { postorder(ans, node.left); ans.add(node.val); }
if ( node.right != null) { postorder(ans, node.right); ans.add(node.val); } } } }
|