Flatten Binary Tree to Linked List

来源:互联网 发布:sql字符串查找函数 编辑:程序博客网 时间:2024/06/01 13:24

Flatten a binary tree to a fake "linked list" in pre-order traversal.

Here we use the right pointer in TreeNode as the nextpointer in ListNode.

 Notice

Don't forget to mark the left child of each node to null. Or you will get Time Limit Exceeded or Memory Limit Exceeded.

Example
              1               \     1          2    / \          \   2   5    =>    3  / \   \          \ 3   4   6          4                     \                      5                       \                        6
最优解要就不能使用额外空间,因此只能进行原地处理。处理时一定要注意指针的变换。树和链表一样,都有大量的指针操作。
java
/** * 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: a TreeNode, the root of the binary tree     * @return:      */    public void flatten(TreeNode root) {        // write your code here        if (root == null) {            return;        }        util(root);    }    private TreeNode util(TreeNode root) {        if (root == null) {            return null;        }        TreeNode left = util(root.left);        TreeNode right = util(root.right);        if (left == null) {            return root;        } else if (left != null && right == null) {            root.left = null;            root.right = left;        } else if (left != null && right != null) {            root.left = null;            root.right = left;            while (left.right != null) {                left = left.right;            }            left.right = right;        }        return root;    }}
python
"""Definition of TreeNode:class TreeNode:    def __init__(self, val):        this.val = val        this.left, this.right = None, None"""class Solution:    """    @param: root: a TreeNode, the root of the binary tree    @return:     """    def flatten(self, root):        # write your code here        if root is None:            return        self.util(root)            def util(self, root):        if root is None:            return None        left = self.util(root.left)        right = self.util(root.right)        if left is None:            return root        elif left is not None and right is None:            root.right = left;            root.left = None        elif left is not None and right is not None:            root.left = None            root.right = left            while left.right is not None:                left = left.right            left.right = right        return root



原创粉丝点击