树Flatten Binary Tree to Linked List(先序遍历)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了树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
The flattened tree should look like:
1 2 3 4 5 6
思路:
按照树的先序遍历顺序把节点串联起来即可。
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {void} Do not return anything, modify root in-place instead. */ var flatten = function(root) { if(root==null){ return; } var stack=[],pre=null; stack.push(root); while(stack.length!=0){ var p=stack.pop(); if(pre!=null){ pre.right=p; pre.left=null } if(p.right){ stack.push(p.right); } if(p.left){ stack.push(p.left); } pre=p; } pre.left=null; pre.right=null; };
以上是关于树Flatten Binary Tree to Linked List(先序遍历)的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode]114. Flatten Binary Tree to Linked List由二叉树构建链表
114 Flatten Binary Tree to Linked List 二叉树转换链表
leetcode 114. 二叉树展开为链表(Flatten Binary Tree to Linked List)
114. Flatten Binary Tree to Linked ListMedium将给定的二叉树转化为“只有右孩子节点”的链表(树)