public int findMax(Node root,Node maxNode,int max){ if(root == null){ return 0; } int leftMax = 0; int rightMax = 0; if(root.leftChild != null){ leftMax = findMax(root.leftChild,root,max); } if(root.rightChild != null){ rightMax = findMax(root.rightChild,root,max); } if(root.data+leftMax+rightMax > max){ max = root.data + leftMax + rightMax; maxNode = root; } return max; }
// 二叉树 typedef struct Tree_ { int data; int val; struct Tree_ * left; struct Tree_ * right; } Tree; // 找到二叉树的子树的节点和的最大值 int findSubTreeMaxSum(Tree *t, int *maxLen) { if(NULL == t || NULL == maxLen) { return 0; } int leftVal = findSubTreeMaxSum(t->left, maxLen); int rightVal = findSubTreeMaxSum(t->right, maxLen); t->val = leftVal + rightVal + t->data; if(t->val > *maxLen) { *maxLen = t->val; } return t->val; }
class TreeNode{
TreeNode left,right;
int tag;
TreeNode(int tag){
this.tag = tag;
}
}
private TreeNode maxRoot = new TreeNode(0);
public int find(TreeNode root){
if(root==null){
return 0;
} else{
int lSum = find(root.left);
int rSum = find(root.right);
if(maxRoot.tag<lSum)
maxRoot = root.left;
if(maxRoot.tag<rSum)
maxRoot = root.right;
return root.tag+lSum+rSum;
}
}
}