larscheng / algo

0 stars 0 forks source link

【Check 46】2024-04-08 - 226. 翻转二叉树 #148

Open larscheng opened 3 months ago

larscheng commented 3 months ago

226. 翻转二叉树

larscheng commented 3 months ago

思路

```java
class Solution2 {
    //递归,分解问题,利用递归栈分别处理左右子树,最终处理根节点左右子树
    //O(n)/O(n)
    public TreeNode invertTree(TreeNode root) {
        if (root==null){
            return null;
        }
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);

        root.left = right;
        root.right = left;

        return root;
    }
}
larscheng commented 3 months ago

思路

迭代 通过广度优先遍历,借助栈或者队列,记录每层节点,遍历栈或者队列内的节点,进行左右子树的节点交换操作

代码

class Solution {
    //迭代,广度优先遍历,队列记录每层的非叶子节点,遍历队列,进行交换左右子树
    //O(n)/O(n)
    public TreeNode invertTree(TreeNode root) {
        if (root==null){
            return null;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()){
            TreeNode temp = queue.poll();
            TreeNode left = temp.left;
            temp.left = temp.right;
            temp.right = left;

            if (temp.left!=null){
                queue.add(temp.left);
            }
            if (temp.right!=null){
                queue.add(temp.right);
            }
        }

        return root;
    }
}