美文网首页
LeetCode题解之翻转二叉树

LeetCode题解之翻转二叉树

作者: l1fe1 | 来源:发表于2020-08-11 08:09 被阅读0次

    翻转二叉树

    题目描述

    翻转一棵二叉树。

    示例 :

    输入:

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

    输出:

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

    解题思路

    方法一:递归

    使用递归来翻转二叉树。

    复杂度分析

    • 时间复杂度:O(n),其中 n 是树中节点的个数,由于每个节点至少被访问一次,因此时间复杂度为 O(n)。
    • 空间复杂度:O(h),最坏情况下递归层数为树的高度 h,因此空间复杂度为 O(h)。

    代码实现

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

    方法二:迭代

    利用栈来进行深度优先遍历,交换每一个节点的左右子树。

    复杂度分析

    • 时间复杂度:O(n)。
    • 空间复杂度:O(n)。

    代码实现

    /**
     * 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 null;
            }
            Stack<TreeNode> stack = new Stack<TreeNode>();
            stack.push(root);
            while (!stack.isEmpty()) {
                TreeNode cur = stack.pop();
                TreeNode temp = cur.left;
                cur.left = cur.right;
                cur.right = temp;
                if (cur.right != null) {
                    stack.push(cur.right);
                }
                if (cur.left != null) {
                    stack.add(cur.left);
                }
            }
            return root;
        }
    }
    

    相关文章

      网友评论

          本文标题:LeetCode题解之翻转二叉树

          本文链接:https://www.haomeiwen.com/subject/nwygrktx.html