LeetCode 226. Invert Binary Tree

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9
to
     4
   /   \
  7     2
 / \   / \
9   6 3   1
分析:又是二叉树的问题,很多二叉树的问题可以用递归算法来解决。先判断当前结点是否为空,此为递归的出口;接下来交换左孩子和右孩子的位置,分别以左孩子和右孩子为结点,继续递归循环判断是否有左孩子或者右孩子,进而继续交换位置。

Java代码如下:

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

解法二:非递归方式

本方法适用于无返回值的解法

 public void invertTree(TreeNode root) {
        
        if(root == null) {
            return;
        }
       
        LinkedList<TreeNode> list = new LinkedList<TreeNode>();
        TreeNode temp = null;
        list.add(root);
        while(list.size() != 0){
            TreeNode node = list.removeFirst();
            temp = node.left;
            node.left = node.right;
            node.right = temp;
            if(node.left != null){
                list.add(node.left);
            }
            if(node.right != null){
                list.add(node.right);
            }
        }
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值