zoukankan      html  css  js  c++  java
  • Solution 15: 树的镜像

    问题描述

    输入一颗BST,将该树转换为它的镜像。

    要求使用递归和非递归两种思路解决。

    解决思路

    非递归基于BST。

    程序

    public class MirrorOfBST {
    public void toMirrorRec(TreeNode root) {
    	if (root == null) {
    		return ;
    	}
    	
    	TreeNode left = root.left;
    	TreeNode right = root.right;
    	
    	root.left = right;
    	root.right = left;
    	
    	toMirrorRec(left);
    	toMirrorRec(right);
    }
    
    public void toMirrorNoRec(TreeNode root) {
    	if (root == null) {
    		return ;
    	}
    	
    	Queue<TreeNode> queue = new LinkedList<TreeNode>();
    	queue.offer(root);
    	
    	while (!queue.isEmpty()) {
    		TreeNode node = queue.poll();
    		if (node != null) {
    			TreeNode left = node.left;
    			TreeNode right = node.right;
    			
    			node.left = right;
    			node.right = left;
    			
    			queue.offer(right);
    			queue.offer(left);
    		}
    	}
    }
    }
    
  • 相关阅读:
    ORM框架
    优酷项目1
    新年第一天
    前端第十天
    前端第九天
    前端第八天
    前端第七天
    前端第六天
    前端第五天
    月亮与六便士
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4617789.html
Copyright © 2011-2022 走看看