一、题目名称java
Invert Binary Tree(反转二叉树)node
二、题目地址code
https://leetcode.com/problems/invert-binary-tree/递归
三、题目内容leetcode
英文:get
Invert a binary tree.io
4 / \ 2 7 / \ / \ 1 3 6 9
toclass
4 / \ 7 2 / \ / \ 9 6 3 1
中文:反转一颗二叉树。import
四、解题方法1二叉树
本题有两种解题方法,第一种是经过递归的方式解决问题,代码行数少,可读性强。
Java代码以下:
/** * LeetCode 226 - Invert Binary Tree * @文件名称 Solution.java * @文件做者 Tsybius2014 * @建立时间 2016年2月11日 下午10:34:59 */ public class Solution { /** * 翻转二叉树 * @param root 二叉树的根 * @return */ public TreeNode invertTree(TreeNode root) { if (root == null) { return root; } TreeNode temp = root.left; root.left = root.right; root.right = temp; invertTree(root.left); invertTree(root.right); return root; } }
五、解题方法2
使用迭代方式解决本问题的Java代码以下:
import java.util.Stack; /** * LeetCode 226 - Invert Binary Tree * @文件名称 Solution.java * @文件做者 Tsybius2014 * @建立时间 2016年2月11日 下午10:34:59 */ public class Solution { /** * 翻转二叉树 * @param root 二叉树的根 * @return */ public TreeNode invertTree(TreeNode root) { if (root == null) { return root; } Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while (!stack.isEmpty()) { TreeNode node = stack.peek(); stack.pop(); if (node.left != null) { stack.push(node.left); } if (node.right != null) { stack.push(node.right); } TreeNode temp = node.left; node.left = node.right; node.right = temp; } return root; } }
END