美文网首页
flatten-binary-tree-to-linked-li

flatten-binary-tree-to-linked-li

作者: 瞬铭 | 来源:发表于2020-04-24 15:30 被阅读0次

    //https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

    • 为什么这个解法可以ac,root都变了?????
        //二叉树先序遍历变变变变变变变
        public void flatten(TreeNode root) {
            if (root == null) {
                return;
            }
    
            flatten(root.left);
    
            flatten(root.right);
    
            TreeNode tmp = root.right;
            root.right = root.left;
            root.left = null;
            while (root.right != null) {
                root = root.right;
            }
            root.right = tmp;
        }
    
    • 为什么这个解法不能ac,明显是可以的????
       // 这个为什么不能AC?????????
        TreeNode res = new TreeNode(-1);
        TreeNode tmp = res;
    
        public void flatten2(TreeNode root) {
            preO(root);
            root = res.right;
        }
    
        public void preO(TreeNode root) {
            tmp.right = new TreeNode(root.val);
            tmp = tmp.right;
            if (root.left != null) {
                preO(root.left);
            }
    
            if (root.right != null) {
                preO(root.right);
            }
        }
    
    • 我心中的完美解法
        public void flatten3(TreeNode root) {
            if (root == null) {
                return;
            }
            flatten3(root.left);
            flatten3(root.right);
    
            TreeNode right = root.right;
            TreeNode tmp = root;
            root.right = root.left;
            root.left = null;
            while (tmp.right != null) {
                tmp = tmp.right;
            }
            tmp.right = right;
        }
    

    相关文章

      网友评论

          本文标题:flatten-binary-tree-to-linked-li

          本文链接:https://www.haomeiwen.com/subject/xstzihtx.html