题解七十

    技术2022-07-11  107

    剑指 Offer 27. 二叉树的镜像

    请完成一个函数,输入一个二叉树,该函数输出它的镜像。 思路:递归法。 遍历二叉树,并交换左、右子节点,即可生成镜像二叉树: (1)若根节点root为空,则返回null; (2)设置一个变量tmp暂时保存左子树的子节点; (3)递归右子树子节点,并保存作为root的左子树子节点; (4)递归左子树子节点,记得是变量tmp,并保存作为root的右子树子节点 (5)返回根节点root。

    class Solution { public TreeNode mirrorTree(TreeNode root) { if (root == null) return null; TreeNode tmp = root.left; root.left = mirrorTree(root.right); root.right = mirrorTree(tmp); return root;

    思路:辅助栈 (1)如果root为空,则返回null; (2)使用一个栈stack,并加入root; (3)使用一个while循环,当栈不为空时: 1、将出栈的结点记为node; 2、如果node的左、右子结点不为空,则往栈中加入node的左、右子结点; 3、设置一个变量tmp保存node的左子结点,并交换node的左、右子结点。 (4)返回根结点root。

    class Solution { public TreeNode mirrorTree(TreeNode root) { if(root == null) return null; Stack<TreeNode> stack = new Stack<>(); stack.add(root); while(!stack.isEmpty()){ TreeNode node = stack.pop(); if(node.left != null) stack.push(node.left); if(node.right != null) stack.push(node.right); TreeNode tmp = node.left; node.left = node.right; node.right = tmp; } return root; } }
    Processed: 0.011, SQL: 9