LintCode 二叉樹的層次遍歷

2021-07-11 18:12:01 字數 2451 閱讀 1822

lintcode:二叉樹的層次遍歷

方法一:二叉樹的層序遍歷,需要借助兩個佇列空間。

"""

definition of treenode:

class treenode:

def __init__(self, val):

self.val = val

self.left, self.right = none, none

""""""

definition of treenode:

class treenode:

def __init__(self, val):

self.val = val

self.left, self.right = none, none

"""class

solution:

""" @param root: the root of binary tree.

@return: level order in a list of lists of integers

"""deflevelorder

(self, root):

# write your code here

if root == none:

return

l1 =

l2 =

if root.left != none:

if root.right != none:

m = 1

while(len(l2) != 0):

n = len(l2)

for i in range(n):

if l2[0].left != none:

if l2[0].right != none:

l2.remove(l2[0])

m += 1

return l1

方法二:

題目要求只用乙個佇列實現,可以考慮把l2放在l1的某個位置,最後再刪除就可以了。

"""

definition of treenode:

class treenode:

def __init__(self, val):

self.val = val

self.left, self.right = none, none

"""class

solution:

""" @param root: the root of binary tree.

@return: level order in a list of lists of integers

"""deflevelorder

(self, root):

# write your code here

if root == none:

return

l1 =

if root.left != none:

if root.right != none:

m = 2

while(len(l1[1]) != 0):

n = len(l1[1])

for i in range(n):

if l1[1][0].left != none:

if l1[1][0].right != none:

l1[1].remove(l1[1][0])

m += 1

l1.remove(l1[1])

return l1

/**

* definition of treenode:

* public class treenode

* }*/public

class solution

linkedlist> l = new linkedlist>();

l.add(new linkedlist());

l.get(0).add(root);

l.add(new linkedlist());

if(root.left != null)

if(root.right != null)

int m = 2;

while(l.get(1).size() != 0)

if(l.get(1).get(0).right != null)

l.get(m).add(l.get(1).get(0));

l.get(1).remove(l.get(1).get(0));

}m += 1;

}arraylist> ans = new arraylist>();

for(int i=0; inew arraylist());

for(int j=0; jget(i).size(); j++)

}ans.remove(1);

return ans;

}}

二叉樹層次遍歷 LintCode

給出一棵二叉樹,返回其節點值的層次遍歷 逐層從左往右訪問 給一棵二叉樹 遍歷結果 3 9,20 15,7 主要思想 為了層次遍歷,就要一層一層地處理資料。先將根節點入隊,之後搜尋其左子樹與右子樹,若非空,則入隊,並將根節點出隊。按照此方法,依此處理。ifndef c69 h define c69 h...

lintcode 二叉樹的層次遍歷

給出一棵二叉樹,返回其節點值從底向上的層次序遍歷 按從葉節點所在層到根節點所在的層遍歷,然後逐層從左往右遍歷 您在真實的面試中是否遇到過這個題?yes 樣例給出一棵二叉樹,3 9 20 15 7按照從下往上的層次遍歷為 15,7 9,20 3 definition of treenode publi...

Lintcode 二叉樹的層次遍歷

給出一棵二叉樹,返回其節點值的層次遍歷 逐層從左往右訪問 樣例 1 輸入 輸出 1 2,3 解釋 1 2 3 它將被序列化為 層次遍歷樣例 2 輸入 輸出 1 2 3 解釋 1 2 3 它將被序列化為 層次遍歷python definition of treenode class treenode ...