二叉树的镜像

来源:互联网 发布:java的annotation 编辑:程序博客网 时间:2024/06/04 23:16

操作给定的二叉树,将其变换为源二叉树的镜像。

IDEA

1.递归算法

判断子树是否为空,为空则return,结束算法;

定义临时变量,交换树左右节点;

然后分别递归当前树的左右子树。

2.非递归算法

用到栈,层序遍历树 (用队列也可以)


CODE

1.递归

public class Solution {    public void Mirror(TreeNode root) {        if(root==null){            return;         }        TreeNode tmp=root.left;        root.left=root.right;        root.right=tmp;        Mirror(root.left);        Mirror(root.right);    }}
2.非递归

import java.util.Stack;public class Solution {    public void Mirror(TreeNode root) {        if(root == null){            return;        }        Stack<TreeNode> st=new Stack<TreeNode>();        st.push(root);        while(!st.isEmpty()){            TreeNode node=st.pop();            if(node.left!=null){                st.push(node.left);            }            if(node.right!=null){                st.push(node.right);            }            if(node.left!=null||node.right!=null){                TreeNode temp=node.left;                node.left=node.right;                node.right=temp;            }                    }    }}


0 0