首页 > 其他 > 详细

226. Invert Binary Tree

时间:2018-04-03 20:52:00      阅读:216      评论:0      收藏:0      [点我收藏+]

原题链接:https://leetcode.com/problems/invert-binary-tree/description/
这是一道有历史典故的算法题目哦:

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();

        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        root.right = new TreeNode(7);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(9);

        root = s.invertTree(root);
        System.out.println(root);
    }

    /**
     * 这道题目还是有历史典故的,下面我的实现是其递归实现版本,也就是做深度优先遍历吧,这也是官方答案的第一种。
     * 官方答案第二种就是使用一个队列来做广度优先遍历来进行处理吧,这里就不在说了!
     *
     * @param root
     * @return
     */
    public TreeNode invertTree(TreeNode root) {
        if (root == null || (root.left == null && root.right == null)) {
            return root;
        }

        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;

        invertTree(root.left);
        invertTree(root.right);

        return root;
    }

}

226. Invert Binary Tree

原文:https://www.cnblogs.com/optor/p/8710835.html

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