Invert Binary Tree

Prompt

Write a function that takes in a Binary Tree and inverts it. In other words, the function should swap every left node in the tree for its corresponding right node.

Each BinaryTree node has an integer value , a left child node, and a right child node. Children nodes can either be BinaryTree nodes themselves or None / null .

Sample Input

Sample Output

在这里插入图片描述


Solution

import java.util.*;

class Program {
	// O(n) time | O(d) space - where d is the depth of the tree
  public static void invertBinaryTree(BinaryTree tree) {
		if (tree == null) {
			return;
		}//A
		// BinaryTree node = tree.left;
		// tree.left = tree.right;
		// tree.right = node;
		swapLeftAndRight(tree);
		invertBinaryTree(tree.left);
		invertBinaryTree(tree.right);
  }
	public static void swapLeftAndRight(BinaryTree tree) {//A
		BinaryTree node = tree.left;
		tree.left = tree.right;
		tree.right = node;
	}

  static class BinaryTree {
    public int value;
    public BinaryTree left;
    public BinaryTree right;

    public BinaryTree(int value) {
      this.value = value;
    }
  }
}

# 1A

务必每次把swap抽象出来

Solution 2

import java.util.*;

class Program {
  public static void invertBinaryTree(BinaryTree tree) {
		ArrayDeque<BinaryTree> queue = new ArrayDeque<BinaryTree>();//A
		queue.addLast(tree);
		while(queue.size() > 0){//A
			BinaryTree currentNode = queue.pollFirst();
			//if (currentNode == null):{
			// if (currentNode == null){
			// 	continue;//C
			// }
			swapLeftAndRight(currentNode);
			if (currentNode.left != null) {//B
				queue.addLast(currentNode.left);
			}
			if (currentNode.right != null) {
				queue.addLast(currentNode.right);
			}	
			// queue.addLast(null);
		}
  }
	
	public static void swapLeftAndRight(BinaryTree tree) {//
		BinaryTree node = tree.left;
		tree.left = tree.right;
		tree.right = node;
	}

  static class BinaryTree {
    public int value;
    public BinaryTree left;
    public BinaryTree right;

    public BinaryTree(int value) {
      this.value = value;
    }
  }
}

# 2A

ArrayDeque的methods

# 2B

Throws: NullPointerException - if the specified element is null

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值