码迷,mamicode.com
首页 > 其他好文 > 详细

*Binary Tree Upside Down

时间:2016-01-20 06:22:51      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

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  

思路:

起始对于每一个节点,相应的操作为:
p.left = parent.right;
p.right = parent;

public class Solution {
    public TreeNode upsideDownBinaryTree(TreeNode root) {
        TreeNode p = root, parent = null, parentRight = null;
        while (p!=null) {
            TreeNode left = p.left;
            p.left = parentRight;
            parentRight = p.right;
            p.right = parent;
            parent = p;
            p = left;
        }
        return parent;
    }
}

reference: http://yuanhsh.iteye.com/blog/2170647

*Binary Tree Upside Down

标签:

原文地址:http://www.cnblogs.com/hygeia/p/5143932.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!