找到二叉树的最深节点

时间:2012-10-26 16:49:42

标签: ruby

我有一个高度方法,能够找到二叉树的高度,但不知道如何返回二叉树的最深节点(如果深度相同则为多个节点)。

BinaryNode.new(1,BinaryNode.new(2,leaf,leaf),BinaryNode.new(3,leaf,leaf))

其中leaf代表空

此树的高度为2,最深的节点为2,3(深度相同)

class BinaryNode 
  include Enumerable
  def initialize(element,lchild,rchild)
    @element, @lchild, @rchild = element, lchild, rchild
  end
  def deepestNode
    if self.nil?
      0
    else
      height1=@lchild.height+1
      height2=@lchild.height+1
    end
      height=[height1,height2].max
      height
    end
  end
end

2 个答案:

答案 0 :(得分:2)

假设:

  • 二叉树实际上是根节点
  • child_nodes将子节点集合作为数组返回

class BinaryNode
  attr_reader :element

  def initialize(element,lchild,rchild)
    @element, @lchild, @rchild = element, lchild, rchild
  end

  def height
    if @lchild.nil? && @rchild.nil?
      return 0
    else
     [@lchild, @rchild].collect {|n| n.nil ? 0 : n.height + 1 }.max      
    end
  end

  def deepest_nodes
    return [self] if self.height == 1

    [@lchild, @rchild].select {|n| !n.nil? && (n.height == self.height - 1)}.collect {|n| n.deepest_nodes}.flatten
  end
end

重构:

class BinaryNode
  attr_reader :element

  def initialize(element,lchild,rchild)
    @element, @lchild, @rchild = element, lchild, rchild
  end

  def child_nodes
    [@lchild, @rchild].compact
  end

  def height
    if self.child_nodes.empty?
      return 0
    else
      self.child_nodes.collect {|n| n.height + 1 }.max      
    end
  end

  def deepest_nodes
    return [self] if self.depth == 1

    self.child_nodes.select {|n| n.height == self.height - 1}.collect {|n| n.deepest_nodes}.flatten
  end
end

获取元素:

BinaryNode.new(1,BinaryNode.new(2,leaf,leaf),BinaryNode.new(3,leaf,leaf)).deepest_nodes.collect {|n| n.element } 

答案 1 :(得分:0)

struct node //structure type
{
    int data;
    struct node *left,*right;
};

from main()
{
    Deepestnode= MaxDepth(root);
}

//return type// function name//
struct node*    MaxDepth (struct node* temp, int depth)
{  
    if(temp->next!=NULL && temp->right!=NULL)
    {
        MaxDepth(temp->left ,depth+1);
        MaxDepth(temp->right,depth+1);
    }
    else if(temp->left==NULL && temp->right!=NULL)
        MaxDepth(temp->right,depth+1);
    else if(temp->left!=NULL && temp->right==NULL)
        MaxDepth(temp->left,depth+1);

    else // temp->left==NULL &&temp->right==NULL   
    {
        if(max<depth)
        {
           max=depth;
           Deepestnode=temp;
        }
        return(Deepestnode);
     }
}