【树】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; };