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

[leetcode]226.Invert Binary Tree

时间:2018-10-14 13:41:53      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:offer   思路   node   etc   tree   递归   binary   非递归   public   

题目

Invert a binary tree.
比如原来的树为 0 1 2
逆转后的树为 0 2 1
也就是把所有结点的左右结点互换

解法一

思路

递归

代码

/**
 * 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 root;
        TreeNode tmp = invertTree(root.right);
        root.right = invertTree(root.left);
        root.left = tmp;
        return root;
    }
}

解法二

思路

非递归,用树的层次遍历

代码

/**
 * 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 root;
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            TreeNode tmp = queue.poll();
            TreeNode left = tmp.left;
            tmp.left = tmp.right;
            tmp.right = left;
            
            if(tmp.left != null) queue.offer(tmp.left);
            if(tmp.right != null) queue.offer(tmp.right);
        }
        return root;
    }
}

[leetcode]226.Invert Binary Tree

标签:offer   思路   node   etc   tree   递归   binary   非递归   public   

原文地址:https://www.cnblogs.com/shinjia/p/9785534.html

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