java 226.反转二叉树(BFS).java
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 226.反转二叉树(BFS).java相关的知识,希望对你有一定的参考价值。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) return root;
TreeNode temp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(temp);
return root;
}
}
public class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
final Deque<TreeNode> stack = new LinkedList<>();
stack.push(root);
while(!stack.isEmpty()) {
final TreeNode node = stack.pop();
final TreeNode left = node.left;
node.left = node.right;
node.right = left;
if(node.left != null) {
stack.push(node.left);
}
if(node.right != null) {
stack.push(node.right);
}
}
return root;
}
}
public class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
final Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
final TreeNode node = queue.poll();
final TreeNode left = node.left;
node.left = node.right;
node.right = left;
if(node.left != null) {
queue.offer(node.left);
}
if(node.right != null) {
queue.offer(node.right);
}
}
return root;
}
}
以上是关于java 226.反转二叉树(BFS).java的主要内容,如果未能解决你的问题,请参考以下文章
java 226.反转二叉树(BFS).java
java 226.反转二叉树(BFS).java
java 226.反转二叉树(BFS).java
java 226.反转二叉树(BFS).java
java 226.反转二叉树(BFS).java
java 226.反转二叉树(BFS).java