二叉树 - 仅打印左分支 - 使用PostOrder Traverse - C ++

时间:2015-11-07 09:52:20

标签: c++ binary-tree cout postorder

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

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 个答案:

答案 0 :(得分:2)

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

所以可能的方法如下:

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);

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

enter image description here

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

  
    

0 1 4 3 8 9 12 11 16 18

  

答案 1 :(得分:1)

这里是postorder遍历的代码

void postorder(BinaryTree *bt)
{
    if(bt!=NULL)
    {
        postorder(t->lp);
        postorder(t->rp);
        //No Code Goes Here
        cout<<bt->data<<"\t";
    }
}

答案 2 :(得分: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;
}

答案 3 :(得分:0)

if(!bt->left()==NULL)
    cout << bt->left()->getData() << "\t";