0

你好!我想知道 if 语句的条件是什么,因此可以使用后序遍历打印二叉树的所有左分支。

template <class dataType>
void PrintLeft (BinaryTree <dataType> * bt) {

 if (!(bt == NULL))

 {

    //traverse left child

    PrintLeft (bt->left());

    //traverse right child

    PrintLeft (bt->right());

    //visit tree

    if(/*no idea what goes here*/)

    cout << bt->getData() <<"\t";

 }

}
4

4 回答 4

2

我了解您只想访问从左分支看到的节点。由于是postorder,所以当您回到正确的分支时,您必须访问它们。因此,正如 πάντα ῥεῖ 所说,您可以使用布尔标志来指示您从哪种类型的分支中发现了节点。

所以一种可能的方法如下:

using Node = BinaryTree <int>; // or another type supporting << operator

void printLeft(Node * root, bool from_left)
{
  if (root == nullptr) // empty tree?
    return; 

  printLeft(root->left, true); // this node must be visited in postorder
  printLeft(root->right, false); // this one must not be visited in postorder

  if (from_left) //  was root seen from a left arc?
    cout << root->getData() << "\t"; // visit only if was seen from a left branch
}

词根有歧义。我假设它不能被打印,因为它不是从左分支(也不是右分支)到达的。

所以第一个电话应该是:

printLeft(root, false);

就像验证一样,对于这棵树:

在此处输入图像描述

该算法产生以下序列作为左后序遍历

0 1 4 3 8 9 12 11 16 18

于 2015-11-07T14:37:41.720 回答
1

这是用于后序遍历的代码

void postorder(BinaryTree *bt)
{
    if(bt!=NULL)
    {
        postorder(t->lp);
        postorder(t->rp);
        //No Code Goes Here
        cout<<bt->data<<"\t";
    }
}
于 2015-11-07T10:01:02.350 回答
0
if(!bt->left()==NULL)
    cout << bt->left()->getData() << "\t";
于 2017-10-31T23:40:16.990 回答
0

试试这个

 void leftViewUtil(struct node *root, int level, int *max_level)
{
    // Base Case
    if (root==NULL)  return;

    // If this is the first node of its level
    if (*max_level < level)
    {
        printf("%d\t", root->data);
        *max_level = level;
    }

    // Recur for left and right subtrees
    leftViewUtil(root->left, level+1, max_level);
    leftViewUtil(root->right, level+1, max_level);
}

// A wrapper over leftViewUtil()
void leftView(struct node *root)
{
    int max_level = 0;
    leftViewUtil(root, 1, &max_level);
}

// Driver Program to test above functions
int main()
{
    struct node *root = newNode(12);
    root->left = newNode(10);
    root->right = newNode(30);
    root->right->left = newNode(25);
    root->right->right = newNode(40);

    leftView(root);

    return 0;
}
于 2015-11-07T10:29:25.263 回答