Flatten a binary tree to a fake "linked list" in pre-order traversal. Here we use the right pointer in TreeNode as the next&#
Description Flatten a binary tree to a fake "linked list" in pre-order traversal. Here we use the right pointer in TreeNode as the
* Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */// 解法一 非递归funcflatten(root*TreeNode){list,cur:=[]int{},&TreeNode{}preorder(root,&list)cur=rootfori:=1;i<len(list);i++{cur.Left=nilcur.Right=&TreeNode...
/*** 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 *right...
LeetCode: 114. Flatten Binary Tree to Linked List 题目描述 Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / \ 2 5 / \ \ 3 4 6 1. 2. 3. 4. 5. The flattened tree should look like:
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 思路: 递归处理每个结点,如果结点左孩子为空,则无需处理。否则先将结点右孩子挂到左孩子最右边的子孙结点,然后将左...
publicvoidPrintBinaryTreeBacRecur(TreeNode<T>root){if(root==null)return;PrintBinaryTreeBacRecur(root.right);PrintBinaryTreeBacRecur(root.left);System.out.print(root.data);} 这里的话,我们不再是打印根节点,而是利用一个全局变量pre,更新当前根节点的右指针为pre,左指针为null。
TreeNode *left; 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 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 \
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 递归法 思路 相当于一次先序遍历, 将先访问的点存储在数组里, 下一个访问的节点为之前访问的点的右子树 ...