如何在遍历二叉树的同时,打印出每个节点的深度
如下图所示的树,要求打印每个节点的数据值和节点的深度。
打印结果如下:
2 1
7 2
2 3
6 3
5 4
11 4
5 2
9 3
4 4
由于树具有天然的递归特性,采用递归算法是解决树问题的常用方法。
算法实现如下:
#include<iostream> using namespace std; struct Node{ int data; Node* left; Node* right; Node(int data, Node* left, Node* right) { this->data = data; this->left = left; this->right = right; } }; void print(Node* root, int height){ if(root==NULL) return; else { cout<<root->data<<"\t"<<height<<endl; print(root->left, height+1); print(root->right, height+1); } } Node* createTree() { Node* n9 = new Node(5,NULL,NULL); Node* n8 = new Node(11,NULL,NULL); Node* n7 = new Node(4,NULL,NULL); Node* n6 = new Node(2,NULL,NULL); Node* n5 = new Node(6,n9,n8); Node* n4 = new Node(9,n7,NULL); Node* n3 = new Node(7,n6,n5); Node* n2 = new Node(5,NULL,n4); Node* n1 = new Node(2,n3,n2); return n1; } int main(){ Node* n = createTree(); print(n,1); return 0; }