226. Invert Binary Tree

来源:互联网 发布:淘宝刷钻兼职可信吗 编辑:程序博客网 时间:2024/05/20 18:01

Invert a binary tree.

这里写图片描述

First of all, consider recursive solution.

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */ class Solution {    public TreeNode invertTree(TreeNode root) {        if(root = null)            return null;        TreeNode lft = root.left;        root.left = invertTree(root.right);        root.right = invertTree(root.lft);        return root;    }}

Also, we can use queue to do BFS.

public TreeNode invertTree(TreeNode root) {    Queue<TreeNode> queue = new LinkedList<>();    if(root = null) return null;    queue.offer(root);    while(!queue.isEmpty()){        TreeNode now = queue.poll();        TreeNode left = now.left;        now.left = now.right;        now.right = left;        if(node.left != null){            queue.offer(now.left);        }        if(node.left != null){            queue.offer(now.right);        }    }    return root;}
原创粉丝点击