Leetcode 114 Flatten Binary Tree to Linked List

xiaoxiao2021-02-28  121

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; } }

转载请注明原文地址: https://www.6miu.com/read-36795.html

最新回复(0)