码迷,mamicode.com
首页 > 其他好文 > 详细

226. Invert Binary Tree

时间:2018-04-03 22:15:15      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:log   print   rtt   new   ring   pre   body   div   []   

原题链接: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

标签:log   print   rtt   new   ring   pre   body   div   []   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!