Leetcode 114 Flatten Binary Tree to Linked List

来源:互联网 发布:软件著作权 设计说明书 编辑:程序博客网 时间:2024/06/05 13:35

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
后序遍历,根节点在顶上,相当于把左右子树连好再加上根节点

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {     private TreeNode prev = null;    public void flatten(TreeNode root) {        if(root == null){            return;        }        flatten(root.left);        flatten(root.right);            root.right = prev;        root.left = null;    prev = root;            }}



原创粉丝点击