649 · 二叉树翻转
描述
给定一个二叉树,其中所有右节点要么是具有兄弟节点的叶节点(有一个共享相同父节点的左节点)或空白,将其倒置并将其转换为树,其中原来的右节点变为左叶子节点。返回新的根节点。
样例
样例1
输入: {1,2,3,4,5}
输出: {4,5,2,#,#,3,1}
说明:
输入是
1
/
2 3
/
4 5
输出是
4
/
5 2
/
3 1
样例2
输入: {1,2,3,4}
输出: {4,#,2,3,1}
说明:
输入是
1
/
2 3
/
4
输出是
4
2
/
3 1
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: the root of binary tree
* @return: new root
*/
TreeNode Newroot ;
public TreeNode upsideDownBinaryTree(TreeNode root) {
// write your code here
if(root == null){
return null ;
}
dfs(root) ;
return Newroot ;
}
public void dfs(TreeNode cur){
if(cur.left != null){
dfs(cur.left) ;
cur.left.left = cur.right ;
cur.left.right = cur ;
cur.left = null ;
cur.right = null ;
}else{
Newroot = cur ;
}
}
}
二叉树翻转算法
1176

被折叠的 条评论
为什么被折叠?



