Function to traverse a binary tree

本小妞迷上赌 提交于 2020-01-05 05:44:09

问题


I'm just starting with trees and am writing a function that traverses a binary tree and visits every node. I'm calling a function called doSomething(TreeNode *thisNode) for each node in the tree. I want to make sure if what I have is correct and that I'm on the right track? Thanks!

void MyTree::Traverse(TreeNode *rt)
{

If(rt != NULL)

Traverse(rt -> left);
doSomething (rt);
Traverse(rt -> right);

}

回答1:


Almost, but not quite.

The if statement in C++ is not capitalized, and you must add brackets as follows:

void MyTree::Traverse(TreeNode *rt)
{
    if(rt != NULL)
    {
        Traverse(rt -> left);
        doSomething (rt);
        Traverse(rt -> right);
    }
}

If you do not add brackets, the statements doSomething(rt) and Traverse(rt->right) will be called no matter if the node is valid or not!




回答2:


It is always a good idea to debug your program with some relevant test cases. In your code, what do you think would happen if rt is not NULL? This should help you figure out if you are doing it right.



来源:https://stackoverflow.com/questions/19417358/function-to-traverse-a-binary-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!