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;}
  1. 还可以用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
原创粉丝点击