递归遍历二叉树并且求和

  • Post author:
  • Post category:其他


递归遍历二叉树并且求和

一、 创建结点

public class TreeNode {


private int value;

private TreeNode lnode;

private TreeNode rnode;

构造方法+get、set方法

public TreeNode() {
	super();
	// TODO Auto-generated constructor stub
}

public TreeNode(int value, TreeNode lnode, TreeNode rnode) {
	super();
	this.value = value;
	this.lnode = lnode;
	this.rnode = rnode;
}

public int getValue() {
	return value;
}

public void setValue(int value) {
	this.value = value;
}

public TreeNode getLnode() {
	return lnode;
}

public void setLnode(TreeNode lnode) {
	this.lnode = lnode;
}

public TreeNode getRnode() {
	return rnode;
}

public void setRnode(TreeNode rnode) {
	this.rnode = rnode;
}

}

二、 递归二叉树的方法

package com.zzy.tree;

public class BinaryTree {


static int sum=0;

//创建sum变量

/**

* 先序遍历

*

* @param root

*/

public int preorder(TreeNode root) {


if (null != root) {


System.out.print(root.getValue() + “\t”);

//获取结点值并求和

sum=sum+root.getValue();

preorder(root.getLnode());

preorder(root.getRnode());

}

return sum;

}

/**
 * 中序遍历
 * 
 * @param root
 */
public void inorder(TreeNode root) {
	if (null != null) {
		inorder(root.getLnode());
		System.out.print(root.getValue() + "\t");
		inorder(root.getRnode());
	}
}

/**
 * 后序遍历递归
 * 
 * @param root
 */
public void postorder(TreeNode root) {
	if (null != root) {
		postorder(root.getLnode());
		postorder(root.getRnode());
		System.out.print(root.getValue() + "\t");
	}
}	

}

三、 测试

package com.zzy.tree;

/**

  • 测试二叉树遍历
  • @author 26444

*/

public class Test {


public static void main(String[] args) {


TreeNode node10 = new TreeNode(10, null, null);

TreeNode node8 = new TreeNode(8, null, null);

TreeNode node9 = new TreeNode(9, null, node10);

TreeNode node4 = new TreeNode(4, null, null);

TreeNode node5 = new TreeNode(5, node8, node9);

TreeNode node6 = new TreeNode(6, null, null);

TreeNode node7 = new TreeNode(7, null, null);

TreeNode node2 = new TreeNode(2, node4, node5);

TreeNode node3 = new TreeNode(3, node6, node7);

TreeNode node1 = new TreeNode(1, node2, node3);

BinaryTree tree = new BinaryTree();

System.out.println(“先序遍历”);

System.out.println(tree);

System.out.println(tree.preorder(node1));

}

}

        初次路过!
                                  初次路过!
                                                         初次路过!



版权声明:本文为weixin_43701424原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。