java 114.将二进制树展平为链接列表(递归).java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 114.将二进制树展平为链接列表(递归).java相关的知识,希望对你有一定的参考价值。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {
        if(root == null) return;
        
        if(root.left == null && root.right == null) return;
        
        Stack<TreeNode> s = new Stack<TreeNode>();
        if(root.right != null){
            s.push(root.right);
        }
        if(root.left != null){
            s.push(root.left);
        }
        
        root.left = null;
        root.right = null;
        
        TreeNode head = root;
    
        while(!s.empty()){
            TreeNode temp = s.pop();
            if(temp.right != null){
                s.push(temp.right);
            }
            if(temp.left != null){
                s.push(temp.left);
            }
            temp.right = null;
            temp.left = null;
            head.right = temp;
            head = head.right;
        }
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {
        helper(root);
    }
    
    private TreeNode helper(TreeNode root) {
        if (root == null) return null;
        if(root.left == null && root.right == null) return root;
        
        TreeNode left = helper(root.left);
        TreeNode right = helper(root.right);
        
        if(left != null) {
            left.right = root.right;
            root.right = root.left;
            root.left = null;
        }
        
        return right == null ? left : right;
    }
}

/*
[]
[1]
[1,2,5,3,4,null,6]
[1,2,null,3,null,4]
[1,2,null,3,null,null,4]
*/

以上是关于java 114.将二进制树展平为链接列表(递归).java的主要内容,如果未能解决你的问题,请参考以下文章

java 114.将二进制树展平为链接列表(递归).java

java 114.将二进制树展平为链接列表(递归).java

java 114.将二进制树展平为链接列表(递归).java

java 114.将二进制树展平为链接列表(递归).java

[LeetCode] 114. 二叉树展开为链表

将嵌套列表展平为 1 深列表