LeetCode 114. Flatten Binary Tree to Linked List (展平二叉树到链接列表)

原题

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

Reference Answer

思路分析

可以看出来变化后每个节点其实都是指向了在先序遍历中的后一个节点。所以就通过栈的方式来先序遍历原树,如果一个节点有左节点,那么把它的右节点压栈(如果有的话),右指针指向原来的左节点;如果一个节点没有子节点,应该把它的右指针指向栈顶的节点。

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def flatten(self, root):
        """
        :type root: TreeNode
        :rtype: void Do not return anything, modify root in-place instead.
        """

        temp_node = []
        while root:
            if root.left:
                if root.right:
                    temp_node.append(root.right)
                root.right, root.left = root.left, None
                
            if not root.right and temp_node:
                root.right = temp_node.pop()
            root = root.right
        

C++ Version Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        vector<TreeNode*> temp_node;
        while(root){
            if (root->left){
                if (root->right){
                    temp_node.push_back(root->right);
                }
                root->right = root->left;
                root->left = NULL;
            }
            if ((!root->left) && (!temp_node.empty())){
                root->right = temp_node.back();
                temp_node.pop_back();
            }
            root = root->right;
        }
    }
};

Note

  • 这道题不是很容易想,仔细体会栈的妙用。

参考文献

[1] https://www.kancloud.cn/xnervwang/leetcode-with-python/438855

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值