For this question, we define the depth of a tree to be the number of levels in it (so an empty tree has depth 0, a tree with a root and only one leaf to has depth 2, etc.)
A "full" binary tree is one in which all the levels of the tree are full 一 every node in the tree has two children, except for the nodes in the bottom level of the tree, which have none. An “unbalanced" binary tree is one in which some levels are not full, and some paths from the root to a leaf are much shorter than the paths to other leaves.
[10 marks] A “difference tree" is a binary tree in which each node contains an integer, every node in the tree has either two children or no children (a leaf), and every non-leaf node contains a value that is the difference between the value in its left child and the value in its right child.
Here is a partial description of a node in that tree:
public class TreeNode {
public int getValue()
public void setValue(/'nt value)
public TreeNode getLeftChild()
public TreeNode getRightChild()
}
Complete the fixDifcTree(..) method so that it will turn a tree into a valid “difference tree", by changing the values in the non-leaf nodes. Assume that every node has either two children or no children, but the values in the non-leaf nodes may be wrong.
Note, fixDifcTree(..) returns the value in the node in its parameter..
public int fixDifcTree(TreeNode root){
}
英文看的头晕。。
(h)[10 个标记]“差异树”是一棵二叉树,其中每个节点包含一个整数,树中的每个节点
要么有两个子节点,要么没有子节点(一个叶),每个非叶节点包含一个值,即其左
子中的值与其右子中的值之间的差值。
下面是该树中节点的部分描述:.
公共类树节点{
公共 INT 获得价值()
公共无效集值(/‘nt 值)
公共树节点获得左子()
公共树节点获得正确的儿童()
}
完成 Fix Difc Tree(.)方法,通过更改非叶节点中的值,使树变成有效的“差异树”。假
设每个节点都有两个子节点或没有子节点,但非叶节点中的值可能是错误的。
注意,Fix Difc Tree(.)返回其参数中节点中的值。
公共 int 修复 Difc 树(树节点根){
对于这个问题,我们将树的深度定义为它的层数(例如,空树的深度为0,而只有根和一个叶的树的深度为2,等等)。“全面”二叉树是一个树的水平都是满一树中的每个节点都有两个孩子,除了节点树的底部水平,哪些没有。“不平衡”二叉树的某些层是不满的,从根到叶的一些路径比到其他叶的路径短得多。(10分)“区别树”是一个二叉树中,每个节点包含一个整数,树中的每个节点都有两个孩子或没有孩子(叶),和每个非叶节点包含一个值之差值在其左孩子和正确的价值。下面是该树中一个节点的部分描述:公共类TreeNode {公共int getValue ()public void setValue(/'nt值)公共TreeNode getLeftChild ()公共TreeNode getRightChild ()}完成fixDifcTree(..)方法,通过更改非叶子节点中的值,将树转换为有效的“差异树”。假设每个节点有两个子节点或没有子节点,但是非叶节点中的值可能是错误的。注意,fixDifcTree(..)在其参数中返回节点的值。public int fixDifcTree(TreeNode root){}
对于每一个节点,我们只要做三件事情,一取左子树值,二取右子树值,三修改自身值。 只是取左子树值和取右子树值的时候需要判断,如果左子树或右子树不是叶子节点,那么需要,重复上述节点操作,直至取到叶子节点,然后依次向上回返数值,就可以了
并不复杂,就是递归嘛
public int fixDifcTree(TreeNode root){ if (root.getLeftChild() != null && root.getRightChild() != null) { return Math.abs(fixDifcTree(root.getLeftChild()) - fixDifcTree(root.getRightChild())); }else { return root.getValue(); } }