如何正确穿越二进制树以返回其高度?

发布于 2025-02-12 13:49:40 字数 369 浏览 1 评论 0原文

我已经开始实施此代码,但是现在我被卡住了。我试图将树的高度从根部恢复到最远的叶子。我能够进入外叶,但不能进入内部叶子。如何将内叶纳入功能以返回最高高度?

static int getHeight(Node root){
  int left = 0;
  int right = 0;
  Node head = root;
  while(root.left != null) {
      root = root.left;
      left++;
  }
  while(head.right != null) {
      head = head.right;
      right++;
  }
return Math.Max(left, right);

I have started implementing this code but now I'm stuck. I'm trying to return the height of the tree from the root to the furthest leaf. I'm able to access the outside leaves but not the inner ones. How can I incorporate the inner leaves in my function in order to return the highest height?

static int getHeight(Node root){
  int left = 0;
  int right = 0;
  Node head = root;
  while(root.left != null) {
      root = root.left;
      left++;
  }
  while(head.right != null) {
      head = head.right;
      right++;
  }
return Math.Max(left, right);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陈甜 2025-02-19 13:49:40

尝试此递归算法:

static int getHeight(Node root){
    int left = 0;
    int right = 0;
    if(root==null) return 0
    left = getHeight(root.left)+1;
    right= getHeight(root.right)+1;
    return Math.Max(left, right);
}

try this recursive algorithm:

static int getHeight(Node root){
    int left = 0;
    int right = 0;
    if(root==null) return 0
    left = getHeight(root.left)+1;
    right= getHeight(root.right)+1;
    return Math.Max(left, right);
}
暮倦 2025-02-19 13:49:40

您可以尝试,例如 b 读取 f irst s earch( bfs )方法(因为您想穿越):

static int getHeight(Node root) {
  if (root == null)
    return 0;

  Queue<Node> agenda = new Queue<Node>();

  agenda.Enqueue(root);

  int result = 0; 

  while (agenda.Count > 0) {
    result += 1;

    for (int i = agenda.Count - 1; i >= 0; --i) {
      var node = agenda.Dequeue();

      if (node.left != null)
        agenda.Enqueue(node.left);
      if (node.right != null)
        agenda.Enqueue(node.right);
    }
  } 

  return result; 
}

You can try, say, Breadth First Search (BFS), let it be non-recursive approach (since you want to traverse):

static int getHeight(Node root) {
  if (root == null)
    return 0;

  Queue<Node> agenda = new Queue<Node>();

  agenda.Enqueue(root);

  int result = 0; 

  while (agenda.Count > 0) {
    result += 1;

    for (int i = agenda.Count - 1; i >= 0; --i) {
      var node = agenda.Dequeue();

      if (node.left != null)
        agenda.Enqueue(node.left);
      if (node.right != null)
        agenda.Enqueue(node.right);
    }
  } 

  return result; 
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文