diff options
author | Michael Hunteman <michael@huntm.net> | 2022-10-02 20:50:02 -0500 |
---|---|---|
committer | Michael Hunteman <michael@huntm.net> | 2022-10-02 20:50:02 -0500 |
commit | 6a0b3fdc5459ad40b40209cf6798e604dd76d3e7 (patch) | |
tree | 0e488713913963d3543e0c6c5c126a6c7a9d54e9 | |
parent | 74375974965fa3a3e43b49a50bbf3ed1dbbc87c7 (diff) |
Add Invert Tree
-rw-r--r-- | InvertTree.java | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/InvertTree.java b/InvertTree.java new file mode 100644 index 0000000..5884275 --- /dev/null +++ b/InvertTree.java @@ -0,0 +1,25 @@ +import java.lang.*; +import java.util.*; +import node.*; + +class InvertTree { + public static TreeNode invertTree(TreeNode root) { + if (root.left == null || root.right == null) + return root; + TreeNode tmp = root.right; + root.right = invertTree(root.left); + root.left = invertTree(tmp); + return root; + } + + public static void main(String[] args) { + TreeNode leftLeaf = new TreeNode(1); + TreeNode lMiddleLeaf = new TreeNode(3); + TreeNode rMiddleLeaf = new TreeNode(6); + TreeNode rightLeaf = new TreeNode(9); + TreeNode leftParent = new TreeNode(2, leftLeaf, lMiddleLeaf); + TreeNode rightParent = new TreeNode(7, rMiddleLeaf, rightLeaf); + TreeNode root = new TreeNode(4, leftParent, rightParent); + System.out.println(invertTree(root).val); + } +} |