[226] Invert Binary Tree
2016-06-27 10:29
267 查看
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; } } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解