二叉树的反转

leetcode原题:(https://leetcode-cn.com/problems/invert-binary-tree/)

题解:使用层序遍历的方式比较合适,其实只要交换每一层的左右子节点,因为交换每一串的左右子节点,左节点的左右子节点也会跟着交换过去,这时候只要把左节点的左子节点与右子节点交换,同时右节点也是如此操作即可达到题目要求。

class Solution {
    public TreeNode invertTree(TreeNode root) {
        // 本题使用层序遍历的方式
        if(root == null){
            return root;
        }
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            TreeNode temp = cur.left;
            
            //   不需要考虑是否为空的,因为为空的话把空交换过去交换过去即可。
            cur.left = cur.right;
            cur.right = temp;
            
            if(cur.left != null){
                queue.offer(cur.left);
            }
            if(cur.right != null){
                queue.offer(cur.right);
            }
        }
        
        return root;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容