Invert a binary tree.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.LinkedList;import java.util.List;import java.util.Queue;public class InvertBinaryTree {public static void main(String[] args) {TreeNode root = new TreeNode(4);root.left = new TreeNode(2);root.right = new TreeNode(7);root.left.left = new TreeNode(1);root.left.right = new TreeNode(3);root.right.left = new TreeNode(6);root.right.right = new TreeNode(9);root = invertTree(root);printTree(root);}static TreeNode invertTree(TreeNode root) {invert(root);return root;}static void invert(TreeNode root) {if (root == null)return;else {invert(root.left);invert(root.right);TreeNode temp;temp = root.left;root.left = root.right;root.right = temp;}}static void printTree(TreeNode root) {Queue<TreeNode> q = new LinkedList<TreeNode>();q.add(root);List<String> vec = new ArrayList<String>();while (!q.isEmpty()) {root = q.poll();if (root == null)vec.add("null");elsevec.add(String.valueOf(root.val));if (root != null) {q.add(root.left);q.add(root.right);}}int j = vec.size() - 1;while (j > 0 && vec.get(j) == "null")j--;for (int i = 0; i < j; i++)System.out.print(vec.get(i) + ",");System.out.print(vec.get(j));}}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data = data;this->left = NULL;this->right = NULL;}};void invert(TreeNode *root){if (root == NULL)return;else{invert(root->left);invert(root->right);TreeNode *temp;temp = root->left;root->left = root->right;root->right = temp;}}TreeNode *invertTree(TreeNode *root){invert(root);return root;}//function to print the treevoid printTree(TreeNode *root){queue<TreeNode *> q;q.push(root);vector<string> vec;while (!q.empty()){root = q.front();q.pop();if (root == NULL)vec.push_back("null");elsevec.push_back(to_string(root->data));if (root != NULL){q.push(root->left);q.push(root->right);}}int j = vec.size() - 1;while (j > 0 && vec[j] == "null")j--;vec.resize(j);for (int i = 0; i < j; i++)cout << vec[i] << ",";cout << vec[j];}int main(){TreeNode *root = new TreeNode(4);root->left = new TreeNode(2);root->right = new TreeNode(7);root->left->left = new TreeNode(1);root->left->right = new TreeNode(3);root->right->left = new TreeNode(6);root->right->right = new TreeNode(9);root = invertTree(root);printTree(root);return 0;}
No comments:
Post a Comment