论坛首页 编程语言技术论坛

java-15.第 15 题: 题目:输入一颗二元查找树,将该树转换为它 即在转换后的二元查找树中,左子树的结点都 用递归和循环两种方法完成树的镜像转换。

浏览 1507 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-01-14  
//use recursion
	public static void mirrorHelp1(Node node){
		if(node==null)return;
		swapChild(node);
		mirrorHelp1(node.getLeft());
		mirrorHelp1(node.getRight());
	}
	//use no recursion but stack
	public static void mirrorHelp2(Node node){
		if(node==null)return;
		Stack<Node> stack=new Stack<Node>();
		stack.add(node);
		while(!stack.isEmpty()){
			node=stack.pop();
			swapChild(node);
			if(node.getLeft()!=null){
				stack.push(node.getLeft());
			}
			if(node.getRight()!=null){
				stack.push(node.getRight());
			}
				
		}
	}

	public static void swapChild(Node node){
		/*not like c/c++,you cannot do this:
		Node temp=left;
		left=right;
		right=temp;
		*/
		Node left=node.getLeft();
		node.setLeft(node.getRight());
		node.setRight(left);
	}
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics