劍指offer之樹專題(一)

2021-10-23 18:36:18 字數 1768 閱讀 7187

題目:

思路:前中->二叉樹,前:根-左-右,中:左-根-右;先得根在中序遍歷中的位置,然後可得左子樹的長度,遞迴遍歷。

class solution 

treenode* recur(vector& preorder, int l1, int r1, vector& inorder, int l2, int r2)

};

題目:

思路:recur(a,b)函式:判斷樹 a中以a為根節點的子樹是否包含樹 b;

終止條件:

當節點 b為空:說明樹 b 已匹配完成(越過葉子節點),因此返回 true;

當節點 a為空:說明已經越過樹 a 葉子節點,即匹配失敗,返回 false ;

當節點 a和 b 的值不同:說明匹配失敗,返回 false ;

返回值:

判斷 a 和 b 的左子節點是否相等,即 recur(a->left, b->left) ;

判斷 a 和 b 的右子節點是否相等,即 recur(a->right, b->right) 

issubstructure(a, b)函式先序遍歷樹 a 中的每個節點 a;

特例處理: 當 樹 a 為空 或 樹 b 為空 時,直接返回 false;

返回值: 若樹 b 是樹 a 的子結構,則必滿足以下三種情況之一,因此用或 || 連線;

以 節點 a 為根節點的子樹 包含樹 bb ,對應 recur(a, b);

樹 b 是 樹 a 左子樹 的子結構,對應 issubstructure(a->left, b);

樹 b 是 樹 a 右子樹 的子結構,對應 issubstructure(a->right, b)

class solution 

bool recur(treenode* a, treenode* b)

};

題目:

思路:對稱二叉樹定義: 對於樹中 任意兩個對稱節點 l 和 r ,一定有:

class solution 

bool recur(treenode* l, treenode* r)

};

題目:

思路:特例處理: 當 root 為空時,直接返回 null;

初始化: 棧(或佇列),本文用棧,並加入根節點 root。

迴圈交換: 當棧 stack 為空時跳出;

出棧: 記為 node ;

新增子節點: 將 node 左和右子節點入棧;

交換: 交換 node 的左 / 右子節點。

class solution 

treenode* mirrortree(treenode* root)

return root;

}};

題目:

思路:中序遍歷的倒序。

class solution 

void dfs(treenode* node,vector&res)

};//非遞迴

class solution

cur = res.top();

res.pop();

k--;

if(k==0) return cur->val;

cur = cur->left;

}return root->val;

}};

劍指offer 雙指標專題

很經典的雙指標題目 讓指標pt 1 先走k步,pt 2出發。這樣當pt 1達到末尾時,pt 2剛好走到倒數第k個。definition for singly linked list.class listnode def init self,x self.val x self.next none cl...

leetcode 劍指 Offer 專題(七)

劍指 offer 專題第七部。題目 劍指 offer 66.構建乘積陣列。定義 begin v 1 i prod a k a 0 times a 1 times dots times a i 1 quad v 1 0 1 v 2 i prod a k a i 1 times dots times a...

劍指offer 樹 遞迴

輸入兩棵二叉樹a,b,判斷b是不是a的子結構。ps 我們約定空樹不是任意乙個樹的子結構 回溯 coding utf 8 class treenode def init self,x self.val x self.left none self.right none class solution de...