【LeetCode-面试算法经典-Java实现】【226-Invert Binary Tree(反转二叉树)】
2015-08-30 06:24
686 查看
【226-Invert Binary Tree(反转二叉树)】
【LeetCode-面试算法经典-Java实现】【所有题目目录索引】
代码下载【https://github.com/Wang-Jun-Chao】
原题
Invert a binary tree.4 / \ 2 7 / \ / \ 1 3 6 9
to
4 / \ 7 2 / \ / \ 9 6 3 1
题目大意
将一棵二叉树进行翻转。解题思路
对每一个结点,将它的左右子树进行交换,再对它的左右子结点进行同样的操作。代码实现
树结点类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) { invertTreeNode(root); } return root; } public void invertTreeNode(TreeNode root) { if (root != null) { TreeNode tmp = root.left; root.left = root.right; root.right = tmp; invertTree(root.left); invertTree(root.right); } } }