https://oj.leetcode.com/problems/binary-tree-upside-down/
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
public TreeNode UpsideDownBinaryTree(TreeNode root)
这一题不是很难,原因就在与它的特殊的树的结构。也就是所有节点的右子树都只有一个节点。也就是实际上没有右子树的概念,只有右子节点。那么循环的做法就是从根节点不停往左节点往下遍历,将parent节点做为当前节点的右节点,兄弟节点作为当前节点的左节点。所以在每一层,你所需要保存的就是parent节点,兄弟节点(parent的右节点),以及下一层的左子节点。根据上述算法,给出解法如下:
public TreeNode UpsideDownBinaryTree(TreeNode root) {
if(root == null)
return null;
TreeNode prev = root, neighbor = root.right, cur = root.left;//cur用来向左遍历,prev表示parent节点,neighbor表示兄弟节点
while(cur != null){
TreeNode cur_neighbor = cur.right, next = cur.left;//我们需要再改变树结构之前先行记录下一层的节点已经兄弟节点。
cur.right = prev;
cur.left = neighbor;
prev = cur;
neighbor = cur_neighbor;
cur = next;
}
root.left = null;
root.right = null;
return prev;
}
}
2018-02-01 Updated:
稍微精简了一下代码,使得代码适用度显得更好。
public TreeNode upsideDownBinaryTree(TreeNode root) {
TreeNode travelNode = root, sibling = null, parent = null;
while (travelNode != null) {
TreeNode nextNode = travelNode.left;
TreeNode nextSibling = travelNode.right;
travelNode.right = parent;
travelNode.left = sibling;
parent = travelNode;
sibling = nextSibling;
travelNode = nextNode;
}
return parent;
}