C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

二分木で最も深い左葉を見つけるためのC++プログラム


左の子と右の子として指定された、最大2つの子を持つ二分木。これは、二分木で最も深い左葉を見つけるためのC++プログラムです

アルゴリズム

Begin.
   function deepestLLeafutil() find the deepest left leaf in a given
   binary tree:  
      lvel is level of current node.
      maxlvel is pointer to the deepest left leaf node found so far  
      isLeft Indicates that this node is left child of its parent  
      resPtr is Pointer to the result  
      If root is equal to Null then  
         Return.  
      Update result if this node is having a left leaf and its level is
      more than the max level of the current result.  
      Recursively call function deepestLLeafutil() for left and right subtrees. 
End.

サンプルコード

#include <iostream>
using namespace std;
struct n {
   int v;
   n *l, *r;
};
void deepestLLeafutil(n *root, int lvel, int *maxvel, bool isLeft, n **resPtr) {
   if (root == NULL)
      return;
   if (isLeft && !root->l && !root->r && lvel > *maxvel) {
      *resPtr = root;
      *maxvel = lvel;
      return;
   }
   deepestLLeafutil(root->l, lvel + 1, maxvel, true, resPtr);
   deepestLLeafutil(root->r, lvel + 1, maxvel, false, resPtr);
}
n* deepestLLeaf( n *root) {
   int maxlevel = 0;
   n *res = NULL;
   deepestLLeafutil(root, 0, &maxlevel, false, &res);
   return res;
}
n *newnode(int d) {
   n *t = new n;
   t->v = d;
   t->l = t->r = NULL;
   return t;
}
int main() {
   n* root = newnode(9);
   root->l = newnode(7);
   root->r = newnode(10);
   root->l->l = newnode(6);
   root->r->l= newnode(8);
   root->r->r = newnode(19);
   root->r->l->r = newnode(4);
   root->r->r->r = newnode(20);
   n *res = deepestLLeaf(root);
   if (res)
      cout << "The deepest left leaf is " << res->v;
   else
      cout << "There is no left leaf in the given tree";
   return 0;
}

出力

The deepest left leaf is 6

  1. 二分探索木で左回転を実行するC++プログラム

    二分探索木は、すべてのノードが次の2つのプロパティを持つソートされた二分木です- ノードの右側のサブツリーには、親ノードのキーよりも大きいすべてのキーがあります。 ノードの左側のサブツリーには、親ノードのキーよりも少ないすべてのキーがあります。各ノードには2つ以上の子を含めることはできません。 木の回転は、二分木の要素の順序を妨げることなく構造を変更する操作です。ツリー内で1つのノードを上に移動し、1つのノードを下に移動します。これは、ツリーの形状を変更したり、小さいサブツリーを下に移動したり、大きいサブツリーを上に移動したりして高さを低くしたりするために使用され、多くのツリー操作の

  2. Pythonの二分木でk長のパスを見つけるプログラム

    一意の値を含む二分木があり、別の値kもあるとすると、ツリー内のkの長さの一意のパスの数を見つける必要があります。パスは、親から子へ、または子から親へのいずれかになります。一部のノードが一方のパスに表示され、もう一方のパスには表示されない場合、2つのパスは異なると見なされます。 したがって、入力が次のような場合 k =3の場合、パスは[12,8,3]、[12,8,10]、[8,12,15]、[3,8,10]であるため、出力は4になります。 これを解決するために、次の手順に従います- 関数dfs()を定義します。これはノードを取ります ノードがnullの場合、 1とk