Given a binary tree, flatten it to a linked list in-place.
这题直观的做法就是先序遍历,一个节点一个节点的塞到list里面,但是为了避免毁掉原本的链接,所以在递归中使用临时变量存储节点
阅读(11) | 评论(0) | 转发(0) |
<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
这题直观的做法就是先序遍历,一个节点一个节点的塞到list里面,但是为了避免毁掉原本的链接,所以在递归中使用临时变量存储节点
- TreeNode * p=NULL;
- void f(TreeNode * root){
- if(root==NULL)
- return;
- p->right=root;
- p=p->right;
- TreeNode * l=root->left;
- TreeNode * r=root->right;
- root->left=NULL;
- f(l);
- f(r);
- }
- void flatten(TreeNode *root) {
- p=new TreeNode(0);
- f(root);
- }
相关热门文章
给主人留下些什么吧!~~
评论热议