二叉树从左向右访问节点
Problem statement:
问题陈述:
Given a Binary Tree, Print the corner nodes at each level. The node at the leftmost and the node at the rightmost.
给定二叉树,在每个级别上打印角节点。 最左边的节点和最右边的节点。
Example:
例:
For this tree output will be: 2 7 5 2 9 5 4
对于此树,输出为: 2 7 5 2 9 5 4
Solution:
解:
Of course the solution includes level order traversal.
当然,解决方案包括级别顺序遍历 。
Algorithm:
算法:
FUNCTION printCorner (root): prints corner nodes (leftmost, rightmost) of the tree
FUNCTION printCorner(根) :打印树的角节点(最左,最右)
Prerequisite: Queue q, input binary tree root
先决条件: 队列q ,输入二叉树根
FUNCTION printCorner(Node *root)
1. Declare a queue to store pointer to tree nodesq;
2. Declare store=0 which will print the rightmost node;
3. Declare temp to store DeQueued element from queue ;
4. Declare count=0 which will help to print the leftmost node;
5. Print the root->data first
6. IF (root->left)
EnQueue (q,root->left);
IF (root->right)
EnQueue (q,root->right);
EnQueue (q, NULL);