9°

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

//方案一:

public class Solution {

public void Mirror(TreeNode root) {
    if(root==null)
        return;
    TreeNode temp=root.left;
    root.left=root.right;
    root.right=temp;
    Mirror(root.left);
    Mirror(root.right);

}

}

//方案二:

import java.util.*;

public class Solution {

public void Mirror(TreeNode root) {
    if(root==null)
        return;
 Stack <TreeNode> stack = new Stack<TreeNode>();
stack.push(root);

while(!stack.isEmpty()){
     TreeNode cur=stack.pop();

	if(cur.left!=null||cur.right!=null){
         TreeNode temp=cur.left;
         cur.left=cur.right;
         cur.right=temp;
     }

     if(cur.left!=null)
         stack.push(cur.left);
     if(cur.right!=null)
         stack.push(cur.right);
}

}

}

本文由【南】发布于开源中国,原文链接:https://my.oschina.net/u/2511906/blog/3136163

全部评论: 0

    我有话说: