力扣原题: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
}