在find(Node root, int level(方法中,if(!=null(语句给我带来了混乱。假设在到达二叉树的最后一个节点时,左侧指向 NULL。语句 find(root.left, ++level( 再次递归调用 find(( 方法。现在,节点指向 NULL。所以 if(root!=null( 不会执行。尽管如此,代码运行良好,下一行代码在 find(( 方法中执行。谁能向我解释当 if(root!=null( 为假时,应该跳过整个 if(( 块?
Java程序寻找最深节点的价值 在给定的二叉树中 类 GFG {
// A tree node
static class Node
{
int data;
Node left, right;
Node(int key)
{
data = key;
left = null;
right = null;
}
}
static int maxLevel = -1;
static int res = -1;
// maxLevel : keeps track of maximum level seen so far.
// res : Value of deepest node so far.
// level : Level of root
static void find(Node root, int level)
{
if (root != null) **//THIS BLOCK SHOULD BE SKIPPED**
{
find(root.left, ++level);
// Update level and resue
if (level > maxLevel)
{
res = root.data;
maxLevel = level;
}
find(root.right, level);
}
}
// Returns value of deepest node
static int deepestNode(Node root)
{
// Initialze result and max level
/* int res = -1;
int maxLevel = -1; */
// Updates value "res" and "maxLevel"
// Note that res and maxLen are passed
// by reference.
find(root, 0);
return res;
}
// Driver code
public static void main(String[] args)
{
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.right.left.right = new Node(7);
root.right.right.right = new Node(8);
root.right.left.right.left = new Node(50);
System.out.println(deepestNode(root));
}
}
如果Node
参数为空,则表示我们已经跑掉了树的尽头,应该"回头"。
空的测试必须去某个地方。将该方法放在顶部意味着只需对其进行一次编码。
另一种选择是在进行递归调用之前对其进行编码,因此我们永远不会传递null
,但是测试必须编码 3 次:一次在左调用之前,一次在右调用之前,在初始调用之前。
root
参数的名称不好,则应称为node
。仅仅因为对它的第一个调用在根中传递,并不意味着我们应该这样命名它。
你的算法在你的二叉树上递归搜索,为了做到这一点,你需要浏览节点,如果你到达一个null
节点,那么你就无法找到离该节点更远的地方。
因此,基本上您需要跳过if
的整个块,因为空节点没有子节点。