加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

114. Flatten Binary Tree to Linked List - Medium

发布时间:2020-12-14 05:17:34 所属栏目:大数据 来源:网络整理
导读:Given a binary tree,flatten it to a linked list in-place. For example,given the following tree: 1 / 2 5 / 3 4 6 The flattened tree should look like: 1 2 3 4 5 6 ? 每个节点的右节点都是preorder traverse的下一个节点 -?应该先?反preorder遍历

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

For example,given the following tree:

    1
   /   2   5
 /    3   4   6

The flattened tree should look like:

1
   2
       3
           4
               5
                   6

?

每个节点的右节点都是preorder traverse的下一个节点 ->?应该先?反preorder遍历 (即node.right->node.left->node) 到最后,从最后开始relink

time: O(n),space: O(height)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    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;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读