Flatten Binary Tree to Linked List

来源:互联网 发布:mac修改淘宝登录密码 编辑:程序博客网 时间:2024/06/01 09:46

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.

该题目的重点是使用递归的方式寻找左右子树的最后一点

/** * 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 leftLast = util(root.left);        TreeNode rightLast = util(root.right);        if (leftLast != null) {            leftLast.left = null;            leftLast.right = root.right;            root.right = root.left;            root.left = null;        }        if (rightLast != null) {            return rightLast;        }        if (leftLast != null) {            return leftLast;        }        return root;    }}