七叶笔记 » golang编程 » Golang刷题Leetcode 114. Flatten Binary Tree to Linked List

Golang刷题Leetcode 114. Flatten Binary Tree to Linked List

题目:Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

把一颗 二叉树 展平成一个 链表

思路

循环遍历左子树,不停的把左子树对接到右子树上去

code

type TreeNode struct {
	Val int
	Left *TreeNode
	Right *TreeNode
}
func flatten(root *TreeNode) {
	node := root
	for node !=  nil  {
		if node.Left != nil {
			tmp := node.Left
			for tmp.Right != nil {
				tmp = tmp.Right
			}
			tmp.Right = node.Right
			node.Right = node.Left
			node.Left = nil
		}
		node = node.Right
	}
}
 

更多内容请移步我的repo:

相关文章