LeetCode—108. Convert Sorted Array to Binary Search Tree 题目 https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/ 将一个递增数组转化为平衡二叉搜索树。平衡二叉搜索树首先是一个二叉搜索树,其次要求每一个节点的左右... ...
代码: /*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode ...
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 click to show hints. Hints: If you notice carefully in the flattened tree, each node's right child points ...
publicvoidflatten(TreeNoderoot){Stack<TreeNode>toVisit=newStack<>();TreeNodecur=root;TreeNodepre=null;while(cur!=null||!toVisit.isEmpty()){while(cur!=null){toVisit.push(cur);// 添加根节点cur=cur.right;// 递归添加右节点}cur=toVisit.peek();// 已经访问到最右的节点了// 在不存在左节...
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 题目大意 # 给定一个
一、原题114. Flatten Binary Tree to Linked List 二、前序遍历 + 展成单链 两步方式 首先通过前序遍历将节点存储到vector 中,然后将vector中的节点展成单链形式。 前序遍历(递归方式实现) /*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right...
TreeNode *right; TreeNode() {} TreeNode(int val) : val(val) {} TreeNode(int val, TreeNode *left, TreeNode *right) : val(val), left(left), right(right) {} }; class Solution { public: void flatten(TreeNode* root) { }
114. Flatten Binary Tree to Linked List 这道题自己一开始的做法是建立一个新链表然后再指向它,想到浪费空间看了题解 思路就是将左子树接在父节点的右子树上,将右子树接在左子树后,这样就是先序遍历的结果了 /** * Definition for a binary tree node....
[leetcode] 114. Flatten Binary Tree to Linked List Description Given a binary tree, flatten it to a linked list in-place. For example, given the following tree: 1 / \ 2 5 / \ \ 3 4 6 1. 2. 3. 4. 5. The flattened tree should look like:...
Can you solve this real interview question? Flatten Binary Tree to Linked List - Given the root of a binary tree, flatten the tree into a "linked list": * The "linked list" should use the same TreeNode class where the right child pointer points to the