二叉树

时间:2015-06-29 04:17:20

标签: java recursion tree binary-tree

我试图逐步了解这个递归程序,每次调用函数时会发生什么,但是想确保我认为代码流是否正确。

    public static int checkHeight(TreeNode root) {
        if (root == null) {
            return 0; // Height of 0
        }

        /* Check if left is balanced. */
        int leftHeight = checkHeight(root.left);
        if (leftHeight == -1) {
            return -1; // Not balanced
        }
        /* Check if right is balanced. */
        int rightHeight = checkHeight(root.right);
        if (rightHeight == -1) {
            return -1; // Not balanced
        }

        /* Check if current node is balanced. */
        int heightDiff = leftHeight - rightHeight;
        if (Math.abs(heightDiff) > 1) {
            return -1; // Not balanced
        } else {
            /* Return height */
            return Math.max(leftHeightJ rightHeight) + 1;
        }
    }
    public static boolean isBalanced(TreeNode root)
    {
        if (checkHeight(root) == -1)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

示例:

           1
        /     \
       2       3
    /    \   /
   4      5  6
 /
7

当程序运行并到达行checkHeight(root.left)时,它现在已经将元素设置为2(root.left),因此这将被递归调用并且堆栈执行暂停,如

|checkHeight(2)| 

然后直到它到达最左边元素的末尾它有

|checkHeight(7)|
|checkHeight(4)|
|checkHeight(2)|

| checkHeight(7)|使用leftHeight = 0 rightHeight = 0弹出。

运行时| checkHeight(4)| - > leftHeight = 1,rightHeight = 0

| checkHeight(2)| - > leftHeight = 2,rightHeight = 1(因为它运行| checkHeight(5)|)

一旦完成,它将返回:Max(2,1)+1 = 3,这将是leftHeight的值。

我的理解是否正确?希望我没有混淆步骤。提前致谢

1 个答案:

答案 0 :(得分:1)

既然您没有提出具体问题,可以用代码来回答,我可以这样说:

递归的关键不是跟随每次调用并坚持调用迷宫,它正在读取代码(用于递归调用)并且相信递归调用应该做什么,它应该做什么。更好地确定单一调用它正在做什么的正确性。然后你可以直接跳过所有“相似”的调用直到结束(如7这里)

另一个是基本规则,必须有一个条件,方法返回 - 基本情况(防止无限循环)

考虑到这两个事实,我认为你可以顺利完成这些步骤(我通过调用来确定。)

提示:您始终可以在调试中使用断点来检查整个过程,而不是手动完成。毕竟,这就是调试的目的。

相关问题