226. Invert Binary Tree

8 篇文章 0 订阅
4 篇文章 0 订阅

反转二叉树

4
/
2 7
/ \ /
1 3 6 9
Output:

4
/
7 2
/ \ /
9 6 3
对左右进行一个反转情况

递归做法

还是套路做法

  1. 对左边节点进行函数操作
  2. 对右边节点进行函数操作
  3. swap 对调做法, root.left , root.right
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root==null || (root.right==null && root.left==null))
                 return root;
        TreeNode left = invertTree(root.left);
        TreeNode right= invertTree(root.right);
        TreeNode tmp= left;
        root.left=  right;
        root.right= left;
        return root;
    }
}

递归使用大量的stack ,应该着重避免使用stack
另一方面其实也可以采用下面这种方法
写法可能更好点

public class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        //默认左边的处理成功了的情况
        invertTree(root.left);
        // 默认右边成功的情况
        invertTree(root.right);
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        return root;
    }
}

DFS 深度优先搜索

使用stack

dequeu.push(头结点情况)
while(队列不为空){
具体操作代码逻辑,先处理根结点
判断左边节点是否为空
不为空,入队列
判断右边节点是否为空
不为空, 入队列
}

public TreeNode invertTree(TreeNode root) {
          
        if (root == null) {
            return null;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        
        while(!stack.isEmpty()) {
            TreeNode node = stack.pop();
            TreeNode left = node.left;
            node.left = node.right;
            node.right = left;
            // 注意在这里处理左右节点的顺序是无所谓的情况
            if(node.left != null) {
                stack.push(node.left);
            }
            if(node.right != null) {
                stack.push(node.right);
            }
        }
        return root;
    
    }
}

使用层次遍历的思想

主要是利用队列, 先进入先出来的思想
关于Java 中Deque 接口的使用可以参考一下的链接, 使用队里的情况
先进入的先处理的的基本情况

层次遍历的代码

  1. 根节点先入队列, 在尾巴加入
  2. while(队列不为空)
  3. 出根节点(先进先出)
  4. 处理步骤三中的处理的节点,完成该过程的判断(主要的逻辑判断情况)
  5. 判断是否有左边节点情况, 加入队列
  6. 判断对否有右边节点情况, 加入队列
public class Solution {
    public TreeNode invertTree(TreeNode root) {
        
        if (root == null) {
            return null;
        }

        final Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while(!queue.isEmpty()) {
            final TreeNode node = queue.poll();
            final TreeNode left = node.left;
            node.left = node.right;
            node.right = left;

            if(node.left != null) {
                queue.offer(node.left);
            }
            if(node.right != null) {
                queue.offer(node.right);
            }
        }
        return root;
    }
}

其他参考链接

Deque
算法步骤参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值