首页 > 其他 > 详细

上下翻转二叉树

时间:2020-03-11 15:23:40      阅读:94      评论:0      收藏:0      [点我收藏+]

https://leetcode-cn.com/problems/binary-tree-upside-down/

1 一个节点 返回原节点

2 两个节点 左变上,上变右

3 三个节点,右变左,左变上,上变右

4 >3 左子树已被翻转,则找到左子树最右节点,右变左,上变右

递归 java 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode turn(TreeNode root) {
        TreeNode temp;
        if (root==null||root.left == null) {
            return root;
        }
        else {
            temp = turn(root.left);
        }
        TreeNode tmpNode = temp;
        while( tmpNode.right !=null )
        {
            tmpNode = tmpNode.right;
        }
        tmpNode.left = root.right;
        tmpNode.right = root;
        root.left = null;
        root.right = null;
        
        return temp;
   
    }
    public TreeNode upsideDownBinaryTree(TreeNode root) {
        if(root==null) return null;
        return turn(root);
    }
}

  

上下翻转二叉树

原文:https://www.cnblogs.com/luiyuying/p/12462246.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!