175. 翻转二叉树--java
2018-01-19 20:39
183 查看
题目:
翻转一棵二叉树
样例
思路:
将root的左右子树的值交换,并递归遍历&交换root的左右子树。
代码:
/**
* 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) {
// write your code here
if(root!=null)
{
TreeNode temp=new TreeNode(0);
temp=root.left;
root.left=root.right;
root.right=temp;
invertBinaryTree(root.left);
invertBinaryTree(root.right);
}
}
}
翻转一棵二叉树
样例
1 1 / \ / \ 2 3 => 3 2 / \ 4 4
思路:
将root的左右子树的值交换,并递归遍历&交换root的左右子树。
代码:
/**
* 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) {
// write your code here
if(root!=null)
{
TreeNode temp=new TreeNode(0);
temp=root.left;
root.left=root.right;
root.right=temp;
invertBinaryTree(root.left);
invertBinaryTree(root.right);
}
}
}
相关文章推荐
- 175. 翻转二叉树
- 二叉树翻转的递归与非递归实现(Java)
- 175.翻转二叉树
- 【LintCode 简单】175. 翻转二叉树
- Lintcode 175. 翻转二叉树
- [LintCode]175.翻转二叉树
- 算法题:lintcode#175 翻转二叉树(java)
- 将一个二叉树左右翻转(Java 版)
- Java求一个二叉树的镜像(即翻转二叉树)
- LintCode - 175.翻转二叉树
- [Java]Invert Binary Tree翻转二叉树
- 【java】实现自己的hashMap--基础hashcode与二叉树
- [数据结构]--二叉树以及Java实现
- Java基础 - 二叉树的顺序存储
- 翻转二叉树
- 二叉树的顺序存储及其Java实现
- 二叉树非递归遍历----前中后及层序的java实现
- Java实现二叉树的遍历
- 层次遍历构造二叉树 java
- Java二叉树的递归,非递归遍历,高度,节点数,叶子节点数