Flatten Binary Tree to Linked List | Java最短代码实现

来源:互联网 发布:如何找猎头知乎 编辑:程序博客网 时间:2024/06/05 19:50

原题链接114. Flatten Binary Tree to Linked List

【思路】

基本思路就是将右子树挂在左子树最右边,并用左子树替换右子树。将root左子树置空,root指向右子树根节点。如此循环,直到root为空:

    public void flatten(TreeNode root) {        while (root != null) {            if (root.left != null) {                TreeNode temp = root.left;                while (temp.right != null)                    temp = temp.right;                temp.right = root.right;                root.right = root.left;                root.left = null;            }            root = root.right;        }    }

225 / 225 test cases passed. Runtime: 1 ms  Your runtime beats 34.42% of javasubmissions.

【补充】

递归解法其实是一种中序遍历,将每个节点的左子树右边,右子树挂在左子树的最右边:

    public void flatten(TreeNode root) {        flattenSubTree(root);    }    public TreeNode flattenSubTree(TreeNode root) {        if (root == null || root.left == null && root.right == null) return root;        TreeNode leftSub = root.left;        TreeNode rightSub = root.right;        root.left = null;        if (leftSub != null) {            root.right = leftSub;            TreeNode temp = flattenSubTree(leftSub);            temp.left = null;            if (rightSub != null) temp.right = rightSub;            else return temp;        }        return flattenSubTree(rightSub);    }
225 / 225 test cases passed. Runtime: 1 ms  Your runtime beats 34.42% of javasubmissions.
欢迎优化!

1 0
原创粉丝点击