Leetcode FlattenBinaryTree Java Python

来源:互联网 发布:unity3d序列帧动画 编辑:程序博客网 时间:2024/06/11 11:20

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

         1        / \       2   5      / \   \     3   4   6
The flattened tree should look like:
   1    \     2      \       3        \         4          \           5            \             6

JAVA:

Java:class TreeNode{        int val;        TreeNode left=null;        TreeNode right=null;        void TreeNode(int val){                this.val=val;        }}        public class FlattenBinaryTree{        public TreeNode reslove(TreeNode root){                int[] ans;                dfs(root,ans);                build(ans);                return ans[0];        }        public void dfs(TreeNode root,int[] ans){                if(root==null){                        return;                }                ans.append(root);                dfs(root.left,ans);                dfs(root.right,ans);        }        public void build(int[] ans){                ans.add(null);                for(int i;i<ans.length-2,i++){                        ans[i].left=null;                        ans[i].right=ans[i+1];                }        }}
Python:

#coding:utf-8class TreeNode:        def __init__(self,val,left,right):                self.val=val                self.left=left                self.right=rightclass FlattenBinaryTree:        def reslove(self,TreeNode root):                ans=[]                dfs(root,ans);                Build(ans);                return ans[0];        def dfs(TreeNode root,int[] ans){                if not root:                        return                ans.append(root)                dfs(root.left,ans)                dfs(root.right,ans)        }        def Build(self,ans):                ans.append(None)                for i in range(len(ans)-1):                        ans[i].left=None                        ans[i].right=ans[i+1]


0 0