翻转二叉树
题目
翻转一棵二叉树
样例
挑战
递归固然可行,能否写个非递归的?
题解
1.递归法
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void invertBinaryTree(TreeNode root) {
if (root == null)
{
return;
}
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
invertBinaryTree(root.left);
invertBinaryTree(root.right);
}
}
2.非递归法
实际就是二叉树的层序遍历,用队列实现。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void invertBinaryTree(TreeNode root) {
if (root == null)
{
return;
}
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty())
{
TreeNode node = q.poll();
TreeNode tmp = node.left;
node.left = node.right;
node.right = tmp;
if (node.left != null)
{
q.add(node.left);
}
if (node.right != null)
{
q.add(node.right);
}
}
}
}
Last Update 2016.9.8