[226] Invert Binary Tree
来源:互联网 发布:中文翻译泰语软件下载 编辑:程序博客网 时间:2024/05/16 13:39
1. 题目描述
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
翻转一个二叉树,即交换二叉树所有的左右节点。
2. 解题思路
树的深度优先访问,交换左右节点后访问孩子节点,交换孩子的左右节点。递归时首先以一个局部作为递归过程中的节点。如选取上例中的节点2,操作到这个节点时,首先需要判断这个节点是否是空(出口),这样做就避免了在递归过程中判断左右孩子是否为空的过程。之后,判断完这个节点是否为空后查看这个节点是否有孩子(出口),若没有孩子也就没有必要交换了,如叶节点3。第三步,交换这个节点的左右孩子,交换这个节点的孩子下的孩子(递归的过程)。
3. Code
/** * 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 null; } // 节点左右都为空时返回当前节点 else if(root.left == null && root.right == null) { return root; } // 节点左右节点有一个是空或都不为空 else { // 交换左右节点 TreeNode tmp = root.left; root.left = root.right; root.right = tmp; // 交换左节点下的孩子 invertTree(root.left); // 交换右节点下的孩子 invertTree(root.right); return root; } }}
0 0
- 226Invert Binary Tree
- 226Invert Binary Tree
- 226 Invert Binary Tree
- 226 Invert Binary Tree
- 226 Invert Binary Tree
- [226]Invert Binary Tree
- 226 Invert Binary Tree
- 226 Invert Binary Tree
- 226Invert Binary Tree
- [226] Invert Binary Tree
- Leetcode[226]-Invert Binary Tree
- LeetCode 226 Invert Binary Tree
- Invert Binary Tree - LeetCode 226
- leetcode[226]:Invert Binary Tree
- leetcode 226: Invert Binary Tree
- Leetcode 226 Invert Binary Tree
- leetcode-226-Invert Binary Tree
- leetcode 226 :Invert Binary Tree
- laravel HTTP路由实例教程(三)—— CSRF攻击原理及其防护
- 数据预处理系列:(七)处理缺失值
- 06. ubuntu 16.04 LTS 安装搜狗输入法
- 07. ubuntu 16.04 LTS 安装谷歌浏览器
- rhce学习第五天
- [226] Invert Binary Tree
- Kafka 0.9 发布
- Docker实战(十五):Docker安装Hive环境
- 使用加盐的散列加密
- SimpleDateFormat warning To get local formatting use getDateInstance(), getDateTimeInstance(), or ge
- 08. ubuntu 16.04 LTS 安装QQ
- commandline 没办法后台运行
- iOS中Bitcode的介绍及配置
- MySQL锁表