LeetCode 156. Binary Tree Upside Down
来源:互联网 发布:怎么去兼职做美工外包 编辑:程序博客网 时间:2024/05/17 07:31
Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.
For example:
Given a binary tree {1,2,3,4,5},
1
/ \
2 3
/ \
4 5
return the root of the binary tree [4,5,2,#,#,3,1].
4
/ \
5 2
/ \3 1
思路:
1.关于树的问题,大致就是recursive 和iterative两种方式去遍历或者修改树的node,这里用recursive。题意有些模糊,先搞清题意:将左节点变成新的根节点,把右节点变成新的左节点,把就的根节点变成新的右节点,即:遍历后根据node位置修改指针。
TreeNode *upsideDownBinaryTree(TreeNode *root) { //recursive if(!root||!root->left) return root; TreeNode* l=root->left,*r=root->right; TreeNode* newRoot=upsideDownBinaryTree(l); l->left=r;//这两行是添加新的左右node指针 l->right=root; root->left=NULL;//这两行是把原来根节点的指针清空 root->right=NULL; return newRoot;}
- 还可以用iterative,
参考http://www.cnblogs.com/grandyang/p/5172838.html
TreeNode *upsideDownBinaryTree(TreeNode *root) { //recursive,因为给定的tree经过flip后很像reverse the linked list的结果,所有在linkedlist中用pre,cur,next三个指针的方法可以借鉴到这里 if(!root||!root->left) return root; TreeNode* cur=root,*pre=NULL,*next=NULL,oldRight=NULL; while(cur){ next=cur->left; cur->left=oldRight; oldRight=cur->right; cur->right=pre; pre=cur; cur=next; } return pre;}
0 0
- leetcode-156.Binary Tree Upside Down
- [Leetcode]156.Binary Tree Upside Down
- Leetcode 156. Binary Tree Upside Down
- LeetCode—156. Binary Tree Upside Down
- LeetCode 156. Binary Tree Upside Down
- [Leetcode] Binary Tree Upside Down
- LeetCode Binary Tree Upside Down
- leetcode Binary Tree Upside Down
- [Leetcode] Binary Tree Upside Down
- leetcode--Binary Tree Upside Down
- LeetCode-Binary Tree Upside Down
- Leetcode Binary Tree Upside Down
- leetcode--Binary Tree Upside Down
- 156. Binary Tree Upside Down
- 156. Binary Tree Upside Down
- [leetcode] 156. Binary Tree Upside Down 解题报告
- LeetCode 156. Binary Tree Upside Down(树的倒转)
- Leetcode 156. Binary Tree Upside Down (Medium) (cpp)
- Spark DataSet介绍
- IntelliJ IDEA中开启断言的方法
- java 浮点类型精度不准的问题(待测试)
- 学习运维——输入输出重定向、vim
- 基础11
- LeetCode 156. Binary Tree Upside Down
- 学习运维——用户、用户组、用户权利下放
- 【JZOJ 4939】平均值
- 涉及JSP页面请求、响应、切换和数据传递的5个内置对象
- 放下 2017
- 莫队(三)核心代码实现
- Leetcode Decode String
- 学习运维——文件权限、控制对文件访问
- poj 2891 Strange Way to Express Integers (中国剩余定理不互质)