递归遍历二叉树并且求和

本文介绍了如何使用Java实现二叉树的递归遍历,并在遍历过程中计算所有节点的和。首先创建了一个TreeNode类表示二叉树节点,接着在BinaryTree类中定义了先序遍历方法,通过递归计算节点值的总和。最后通过Test类进行测试,输出先序遍历的结果和节点和。
摘要由CSDN通过智能技术生成

递归遍历二叉树并且求和

一、 创建结点

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(Tre

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值