在二叉树java中找到最右边的孩子

时间:2014-09-08 20:56:41

标签: java recursion binary-tree

我在找到二叉树中的最后一个元素(最右边的孩子)时遇到了一些麻烦。

这是我到目前为止所做的:

public Node findLastElement(Node root) {
  Node x = root;
  if (x != null)
      findLastElement(x.right);
  return x;
}

如果我打印元素,打印的最后一个元素是最后一个元素,但我似乎无法"得到"那个元素。当我尝试在循环后返回x时,我得到一个nullpointer。如何保存最后一个元素并将其返回?

5 个答案:

答案 0 :(得分:6)

您可以递归获取最右边的元素:

public Node findLastElement(Node root) {
    if (root == null) {
        return null;
    }
    if (root.right == null) {
        return root;
    }
    return findLastElement(root.right);
}

你也可以迭代地做。迭代通常在内存方面更好,因为它没有使用递归创建的额外堆栈帧。

public Node findLastElement(Node root) {
    if(root == null) {
        return null;
    }
    Node x = root;
    while(x.right != null) {
        x = x.right;
    }
    return x;
}

并不需要临时变量x。由于java通过值传递引用(它们是原始引用的副本),我们对输入参数root所做的任何赋值都是本地的,不会在findLastElement方法之外反映。

public Node findLastElement(Node root) {
    if(root == null) {
        return null;
    }
    while(root.right != null)
        root = root.right;
    return root;
}

答案 1 :(得分:4)

您需要返回递归函数调用的结果。

E.g。

public Node findLastElement(Node x) {
  if (x != null && x.right != null)
      return findLastElement(x.right);
  else
      return x;
}

答案 2 :(得分:2)

如果使用null参数调用方法,则附加检查x

public Node findLastElement(Node root) {
  Node x = root;

  if (x != null && x.right != null) {
      return findLastElement(x.right);
  } else {
      return x;
  }

}

答案 3 :(得分:0)

您需要检查当前节点是否为非空且它的最右侧节点是非空的,这将考虑当传递的第一个节点也为空时的情况。

public Node findLastElement(Node root) {
    Node x = root;
        if(x != null){
            if (x.right != null)
                return findLastElement(x.right);
        }
    return x;
}

答案 4 :(得分:0)

我更喜欢简单方法中的单个return语句,因此它看起来像:

public Node findLastElement(Node root) {
    return root != null && root.right != null ? findLastElement(root.right) : root;
}