亚马逊面试题2(二叉树)

发布时间:2016-12-11 22:03:36 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"亚马逊面试题2(二叉树)",主要涉及到亚马逊面试题2(二叉树)方面的内容,对于亚马逊面试题2(二叉树)感兴趣的同学可以参考一下。

问题:给定一个二叉树,让每一个叶子节点的右指针指向下一个叶子节点 #include<iostream> using namespace std; class TreeNode{ public: TreeNode* left; TreeNode* right; int val; TreeNode(int); }; TreeNode::TreeNode( int value ) { left = NULL; right = NULL; val = value; } void customInorderTraversal(TreeNode *node , TreeNode **prevleaf){ if(node->left == NULL && node->right == NULL){ if(*(prevleaf) != NULL){ (*(prevleaf))->right = node; } *(prevleaf) = node; }else if(node->left == NULL){ customInorderTraversal(node->right,prevleaf); }else if(node->right == NULL){ customInorderTraversal(node->left,prevleaf); }else{ customInorderTraversal(node->left,prevleaf); customInorderTraversal(node->right,prevleaf); } } void createTree(TreeNode* node){ TreeNode* h; h = node; h->left = new TreeNode(2); h->right = new TreeNode(3); h->left->left = new TreeNode(4); h->left->right = new TreeNode(5); h->right->left = new TreeNode(6); h->right->right = new TreeNode(7); h->left->left->left = new TreeNode(8); h->left->left->right = new TreeNode(9); } void displayLeafs(TreeNode * rootnode){ TreeNode* root = rootnode; while(root->left != NULL){ //cout<<root->val<<" "; root = root->left; } cout<<"\n叶子节点的路径为 : "; while(root != NULL){ cout<<root->val<<" "; root = root->right; } } int main(){ TreeNode* rootnode = (TreeNode*) new TreeNode(1); cout<<"根节点为:"<<rootnode->val<<endl; createTree(rootnode); TreeNode* prev = NULL; customInorderTraversal(rootnode,&prev); displayLeafs(rootnode); }

上一篇:PCQQ2013 0828涉及到的CRC校验算法[.net
下一篇:How to collect HW info by Ipmitool

相关文章

相关评论