leetcode試題總結 8

2021-07-22 03:48:30 字數 1900 閱讀 7266

257. binary tree paths

題意:給定乙個二叉樹,返回其從根到葉子節點的每一條路徑

/**

* definition for a binary tree node.

* struct treenode

* };

*/class solution

if(root->left)

binarytree(result,root->left,str + "->" + to_string(root->left->val));

if(root->right)

binarytree(result,root->right,str + "->" + to_string(root->right->val));

}vectorbinarytreepaths(treenode* root)

};

class solution
總結:從根節點開始,利用遞迴的方法將每個結點的字元資訊儲存到vector容器中。

235. lowest common ancestor of a binary search tree

題意:給定乙個二叉搜尋樹,找出兩個給定結點的最小公共祖先。

/**

* definition for a binary tree node.

* struct treenode

* };

*/class solution

};

總結:因為是二叉搜尋樹,所以結點的大小順序已經是排好的了,所以這裡可用遞迴思想:

1.如果根節點或給定的結點q、p之一為空,則返回空。

2.判斷p,q與根節點的大小關係,如果二者都小於根節點,說明最小公共祖先位於根節點的左子樹上,因此將根              結點換成其左子樹結點進行迭代。如果二者都大於根結點,說明最小公共祖先位於根節點的右子樹上,因此                將根結點換成其右子樹結點進行迭代。如果去p,q乙個大於根結點,乙個小於跟結點,說明最小公共祖先就是              跟結點,返回跟結點即可。

226. invert binary tree

題意:給定乙個二叉樹,使整個二叉樹的所有結點的左右結點反轉。

// my answer

/** * definition for a binary tree node.

* struct treenode

* };

*/class solution

return root;

}};

recursive

treenode* inverttree(treenode* root)

return root;

}non-recursive

treenode* inverttree(treenode* root)

}return root;

}

總結:用遞迴的方法,始終有一種摸不著套路的感覺。這道題遞迴的思路應該算是比較清晰的,一次交換每一層每乙個結點的左右結點即可。答案中還給出了一種利用棧的迭代的方法。

112. path sum

題意:給定乙個二叉樹及乙個值,判斷二叉樹中有無從根節點到葉子節點的路徑的和等於給定的值,若有返回true,無返回false.

/**

* definition for a binary tree node.

* struct treenode

* };

*/class solution

};

class solution 

};

leetcode 試題總結 5

本篇開始說明棧和佇列的題目 232.implement queue using stacks 功能 使用棧結構執行佇列結構的操作 注意 只能使用棧結構的標準操作 即push pop peek size empty。class queue removes the element from in fro...

2018前端必考面試題總結8

官方 解釋 所謂 閉包 指的是乙個擁有許多變數和繫結了這些變數的環境的表示式 通常是乙個函式 因而這些變數也是該表示式的一部分。通俗來講 就是函式a的內部函式b,被函式a外部的乙個變數引用的時候,就建立了乙個閉包。functiona return b var c a 變數c實際上是指向了函式b c ...

爬蟲總結8

非同步是過程,非阻塞強調的是狀態from pymongo import mongoclient client mongoclient host port uri mongodb 賬號 密碼 127.0.0.1 client mongoclient uri,port 27017 連線物件 col cl...