java、go分别实现二叉树的镜像

力扣原题:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/

入参:

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


出参:

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

解题思路:

根据二叉树镜像的定义可知:我们要做的核心工作交换每个节点的左右子节点。因此我们可以有两种思路解题

一、递归:dfs深度优先遍历,自下而上交换左右子节点

java版本实现:

 public TreeNode mirrorTreeNode(TreeNode root) {
        if (root == null) return root;
        TreeNode temp = root.left;
        root.left = mirrorTreeNode(root.right);
        root.right = mirrorTreeNode(temp);
        return root;
    }

go版本实现:

/**
* @Description: 二叉树的镜像,递归实现,自下而上交换
*/
func mirrorTree(root *TreeNode) *TreeNode  {
	if root == nil {
		return root
	}
	left := root.Left
	root.Left = mirrorTree(root.Right)
	root.Right = mirrorTree(left)
	return root
}


/**
* @Description:定义二叉树节点
 */
type TreeNode struct {
	Val int
	Left *TreeNode
	Right *TreeNode
}

 

二、借助栈:实现自上而下交换左右子节点

java版本实现:

 /**
     * @Description: 采用辅助栈, 自上而下
     * @return: treenod.TreeNode
     */
    public TreeNode mirrorTreeNodeByStack(TreeNode root) {
        if (root == null) return null;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);

        while (!stack.empty()) {
            TreeNode currentRoot = stack.pop();
            TreeNode left = currentRoot.left;
            TreeNode right = currentRoot.left;

            //入栈
            if (left != null) {
                stack.push(left);
            }
            if (right != null) {

                stack.push(right);
            }

            //交换
            currentRoot.left = right;
            currentRoot.right = left;
        }
        return root;
    }

go版本实现:因为golang中并没有内置的stack,可以借助内置的双链表来实现

func mirrorByStack(root *TreeNode) *TreeNode  {
	if root == nil {
		return root
	}
	//双链表实现栈
	stack := list.New()
	stack.PushFront(root)
	for {
		if stack.Len() <= 0 {
			break
		}
		currentNode := stack.Remove(stack.Front()).(*TreeNode)
		//栈里有数据,则继续执行
		left := currentNode.Left
		right := currentNode.Right
		if left != nil {
			stack.PushFront(left)
		}
		if right != nil {
			stack.PushFront(right)
		}

		//交换
		currentNode.Left = right
		currentNode.Right = left
	}
	return root
}


/**
* @Description:定义二叉树节点
*/
type TreeNode struct {
	Val int
	Left *TreeNode
	Right *TreeNode
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值