首页 > 其他 > 详细

LeetCode-226.Invert Binary Tree

时间:2019-02-25 16:09:08      阅读:144      评论:0      收藏:0      [点我收藏+]

Invert a binary tree.

Example:

Input:

     4
   /     2     7
 / \   / 1   3 6   9

Output:

     4
   /     7     2
 / \   / 9   6 3   1
public TreeNode invertTree(TreeNode root) {//树 递归 my
        if (null!=root){
            TreeNode left = invertTree(root.left);
            TreeNode right = invertTree(root.right);
            root.left=right;
            root.right=left;
        }
        return root;
    }  

 

非递归的方法

public TreeNode invertTree(TreeNode root) {
    if (root == null) return null;
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.add(root);
    while (!queue.isEmpty()) {
        TreeNode current = queue.poll();
        TreeNode temp = current.left;
        current.left = current.right;
        current.right = temp;
        if (current.left != null) queue.add(current.left);
        if (current.right != null) queue.add(current.right);
    }
    return root;
}

  

  

LeetCode-226.Invert Binary Tree

原文:https://www.cnblogs.com/zhacai/p/10431018.html

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