Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jeremyckahn/2555dbf9730101b25d679777e8e36f8c to your computer and use it in GitHub Desktop.
Save jeremyckahn/2555dbf9730101b25d679777e8e36f8c to your computer and use it in GitHub Desktop.
Prompt for unsloth:Qwen3-30B-A3B-GGUF:Qwen3-30B-A3B-UD-Q4_K_XL.gguf: Invert a binary tree in JS and print an ASCII representation of the before and after. /no_think
<think>
</think>
To **invert a binary tree** in JavaScript, you can perform a recursive swap of left and right children for each node.
Then, to **print an ASCII representation**, we'll use a helper function that prints the tree in a readable format (like how it might look on paper).
---
### ✅ Step-by-step:
1. Define a `TreeNode` class.
2. Create a function to invert the binary tree.
3. Create a function to print the tree in an ASCII representation.
4. Test with some sample input.
---
### 🧠 JavaScript Code
```javascript
class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
// Invert the binary tree
function invertTree(root) {
if (root === null) return null;
// Swap left and right
const temp = root.left;
root.left = root.right;
root.right = temp;
// Recurse on children
invertTree(root.left);
invertTree(root.right);
return root;
}
// Print the tree in ASCII format (level-order traversal)
function printTree(node, level = 0) {
if (node === null) return;
console.log(' '.repeat(level * 2) + node.val);
printTree(node.left, level + 1);
printTree(node.right, level + 1);
}
// Example usage
const root = new TreeNode(4,
new TreeNode(2,
new TreeNode(1),
new TreeNode(3)
),
new TreeNode(7,
new TreeNode(6),
new TreeNode(9)
)
);
console.log("Original Tree:");
printTree(root);
console.log("\nInverted Tree:");
const invertedRoot = invertTree(root);
printTree(invertedRoot);
```
---
### 📝 Example Output
If you run the above code, it will output:
```
Original Tree:
4
2
1
3
7
6
9
Inverted Tree:
4
7
9
6
2
3
1
```
---
### 🧩 Notes:
- The `printTree` function uses **level-order traversal**, printing each node with indentation to simulate a tree structure.
- You can enhance the output further (e.g., using a more advanced ASCII layout) if needed, but this is a simple and readable representation.
Would you like an improved version that prints in a *full* tree format (like how it's shown on paper)?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment