fork download
  1. /* package whatever; // don't place package name! */
  2. import java.util.*;
  3. import java.lang.*;
  4. import java.io.*;
  5.  
  6. /* Name of the class has to be "Main" only if the class is public. */
  7. public class Main {
  8.  
  9. public static void main (String[] args) throws java.lang.Exception {
  10. TreeNode<Integer> root = createTree();
  11. printTree(root);
  12. System.out.println();
  13. System.out.println("overwritten: " + overwriteall(root, 7, 10));
  14. printTree(root);
  15. System.out.println();
  16. }
  17.  
  18. public static TreeNode<Integer> createTree() {
  19. TreeNode<Integer> root = new TreeNode<Integer>(1);
  20.  
  21. root.left = new TreeNode<Integer>(2);
  22. root.left.left = new TreeNode<Integer>(3);
  23. root.left.right = new TreeNode<Integer>(4);
  24.  
  25. root.right = new TreeNode<Integer>(7);
  26. root.right.left = new TreeNode<Integer>(7);
  27. root.right.right = new TreeNode<Integer>(7);
  28.  
  29. return root;
  30.  
  31. }
  32.  
  33. public static <T> void printTree(TreeNode<T> root) {
  34.  
  35. // base case
  36. if(root == null) { return; }
  37.  
  38. // in order traversal
  39. printTree(root.left);
  40.  
  41. System.out.print(root.key);
  42. System.out.print(' ');
  43.  
  44. printTree(root.right);
  45. }
  46.  
  47. public static <T> boolean overwriteall(TreeNode<T> root, T find, T replace) {
  48. // base case
  49. if(root == null) { return false; }
  50.  
  51. // pre order traversal
  52. boolean found = false;
  53. if(root.key.equals(find)) {
  54. found = true;
  55. root.key = replace;
  56. }
  57.  
  58. // you cannot use || since that will short circuit
  59. // and therefore the right part of the tree will not be processed
  60. // if their is an element on the left part already
  61. return found | overwriteall(root.left, find, replace) | overwriteall(root.right, find, replace);
  62. }
  63.  
  64. public static class TreeNode<T> {
  65. public T key;
  66. public TreeNode<T> left;
  67. public TreeNode<T> right;
  68.  
  69. public TreeNode(T key) {
  70. this.key = key;
  71. }
  72. }
  73. }
Success #stdin #stdout 0.04s 320576KB
stdin
Standard input is empty
stdout
3 2 4 1 7 7 7 
overwritten: true
3 2 4 1 10 10 10