首页 > 其他 > 详细

LeetCode 114. 二叉树展开为链表(Flatten Binary Tree to Linked List)

时间:2019-05-19 22:29:22      阅读:142      评论:0      收藏:0      [点我收藏+]

114. 二叉树展开为链表
114. Flatten Binary Tree to Linked List

题目描述
Given a binary tree, flatten it to a linked list in-place.
给定一个二叉树,原地将它展开为链表。

LeetCode114. Flatten Binary Tree to Linked List

For example, given the following tree:

    1
   /   2   5
 / \   3   4   6

The flattened tree should look like:

1
   2
       3
           4
               5
                   6

Java 实现
TreeNode Class

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

Iterative Solution

import java.util.Stack;

class Solution {
    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode curr = stack.pop();
            if (curr.right != null) {
                stack.push(curr.right);
            }
            if (curr.left != null) {
                stack.push(curr.left);
            }
            if (!stack.isEmpty()) {
                curr.right = stack.peek();
            }
            curr.left = null;  // don't forget this!
        }
    }
}

Recursive Solution

class Solution {
    private TreeNode prev = null;

    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        flatten(root.right);
        flatten(root.left);
        root.right = prev;
        root.left = null;
        prev = root;
    }
}

相似题目

参考资料

LeetCode 114. 二叉树展开为链表(Flatten Binary Tree to Linked List)

原文:https://www.cnblogs.com/hglibin/p/10890933.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!