BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / java / #21342同步于 2012/2/10
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖

java如何实现C的这个特性:C语言中,传递给函数的是参数的地址

web
2012/2/10镜像同步4 回复
如以下代码,判断二叉树是否平衡。注意到int left,right的用法。如果想用java来写,如何实现呢,新建一个类吗(left,right作为类的成员,通过类方法修改left和right的值)? bool IsBalanced(BinaryTreeNode* pRoot, int* pDepth) { if(pRoot == NULL) { *pDepth = 0; return true; } int left, right; if(IsBalanced(pRoot->m_pLeft, &left) && IsBalanced(pRoot->m_pRight, &right)) { int diff = left - right; if(diff <= 1 && diff >= -1) { *pDepth = 1 + (left > right ? left : right); return true; } } return false; }
订阅后,新回复会通过你的通知中心匿名送达。
4 条回复
manted机器人#1 · 2012/2/10
【 在 web 的大作中提到: 】 : 如以下代码,判断二叉树是否平衡。注意到int left,right的用法。如果想用java来写,如何实现呢,新建一个类吗(left,right作为类的成员,通过类方法修改left和right的值)? : bool IsBalanced(BinaryTreeNode* pRoot, int* pDepth) : { : ................... bool IsBalanced(BinaryTreeNode* pRoot, int* pDepth) { if(pRoot == NULL) { *pDepth = 0; return true; } int left, right; if(IsBalanced(pRoot->m_pLeft, &left) && IsBalanced(pRoot->m_pRight, &right)) { int diff = left - right; if(diff <= 1 && diff >= -1) { *pDepth = 1 + (left > right ? left : right); return true; } } return false; } 不懂帮顶
michael2008机器人#2 · 2012/2/10
从面向对象的抽象出发,把节点抽象成类,写方法。。。没法,面向对象的短板,学C的人肯定巨抑郁,本身简单高效的非得去包装下。。。
wks机器人#3 · 2012/2/10
就是要返回两个值。不如用这个作为返回值呢: public class BalancednessAndDepth { private boolean balanced; private int depth; // Getters and setters here... }
web机器人#4 · 2012/2/11
这样写可以: public static boolean isBalanced(Node node,AuxClass aux){ if(node==null){ aux.depth=0; return true; } AuxClass left=new AuxClass(); AuxClass right=new AuxClass(); //get leftTreeDepth and rightTreeDepth of a node.If the 'diff' is bigger than 1,return false;true otherwise if(isBalanced(node.getLeft(),left)&&isBalanced(node.getRight(),right)){ int leftDepth=left.depth; int rightDepth=right.depth; int diff=leftDepth-rightDepth; if(diff==1||diff==-1||diff==0){ aux.depth=leftDepth>rightDepth?leftDepth+1:rightDepth+1; return true; } } return false; } public static class AuxClass{ private int depth; }