首页 > 其他 > 详细

[LeetCode] NO.226 Invert Binary Tree

时间:2016-08-14 14:40:39      阅读:138      评论:0      收藏:0      [点我收藏+]

[题目] 

Invert a binary tree.

     4
   /     2     7
 / \   / 1   3 6   9

to

     4
   /     7     2
 / \   / 9   6 3   1

[题目解析] 还是二叉树的问题,这类题目都可以拆解成 处理当前节点,处理左子树,处理右子树 几个子问题。
而左子树和右子树的问题也就是当前这类问题,可以使用递归。这种思路是比较简单直接的。参考求二叉树最大深度问题。代码如下。

private class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) {val = x;}
}

public TreeNode invertTree(TreeNode root) {
    if(null == root) return null;
    if(null == root.left && null == root.right) return root;
    TreeNode tmp = invertTree(root.left);
    root.left  = invertTree(root.right);
    root.right = tmp;
    return root;
}
    

 

 

[LeetCode] NO.226 Invert Binary Tree

原文:http://www.cnblogs.com/zzchit/p/5770144.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!