[英]How Does In Order Binary Tree Traversal Work? C++
void IntBinaryTree::insert(TreeNode*& tree, int num) {
//[1] Base Case: is the node empty?
if (!tree) { // if node is empty, create one
tree = new TreeNode(num);
return;
}
//[2] Does the value already exist in the tree?
if (tree->value == num)
return;
//[3] node passed not empty? If less than head pass left otherwise right
if (tree->value > num)
insert(tree->left, num);
else
insert(tree->right, num);
}
void IntBinaryTree::displayInOrder(TreeNode* root) {
if (root) {
displayInOrder(root->left);
std::cout << root->value << " ";
displayInOrder(root->right);
}
}
我想了解為什么displayInOrder
function 有效? 假設有一棵樹看起來像這樣:
5
/ \
3 7
/ \ / \
1 4 6 8
為了按數字順序顯示這棵樹,您需要先讀取左邊最左邊的值,然后是根,然后是右邊最左邊的值,最后是最右邊的值。
現在, displayinorder
function 以if
條件開始。 簡單地說,如果輸入不等於 false,則繼續向左。 我的問題是,一旦我們到達最左邊的值(在我上面的示例中為 1),下一次調用“ displayInOrder(root->left);
”不會等於最左邊的值 1(默認情況下為NULL
) NULL
不會使if
條件為假嗎?
這個function怎么就知道不調用最左邊的值1呢?
這是因為遞歸。 在displayInOrder(root->left)的遞歸調用中,設置當前根指針指向root->left。 但是我們知道 root(對於這個上下文,它是 root->left from the previous call)指向 null。所以,if 塊沒有被執行並且遞歸執行回溯,go 到它的調用者 function(當 root 不是null,值為 1)。 然后它執行下一行代碼,將 1 打印到控制台。 然后類似的繼續,直到遞歸終止。 希望這可以幫助!
它實際上調用顯示node(1)的左子節點,但它是NULL或nullptr,我們知道if(NULL)
等同於if(false)
,因此displayinorder(node1->left)
的調用不會進入if 直接返回給調用者displayinorder(node1)
。
// stack of function calls
display(5)
->display(3)
-> display(1)
-> display(NULL)
print 1
-> display(NULL)
print 3
-> display(4)
-> display(NULL)
print 4
-> display(NULL)
print 5
-> display(7)
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.