LintCode(Flatten Binary Tree to Linked List)翻转二叉树为链表 的变体

来源:互联网 发布:依云软件官方网站 编辑:程序博客网 时间:2024/06/05 05:55

Flatten Binary Tree to Linked List (深度优先搜索)

 翻转二叉树为链表

/** * 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: nothing     */    public void flatten(TreeNode root) {        if(root == null)return;        flattenSubTree(root);    }        private TreeNode flattenSubTree(TreeNode root){       if (root == null){            return null;        }else if (root.left == null && root.right == null){            return root;        }else{            TreeNode left = root.left;            TreeNode right = root.right;            root.left = null;            if (left != null){                root.right = left;                TreeNode temp = flattenSubTree(left);                temp.left = null;                if (right != null){                    temp.right = right;                }else{                    return temp;                }            }            return flattenSubTree(right);        }     }}





0 0