leetcode_01
minimum-depth-of-binary-tree
求二叉樹的最小深度
class Solution
{
public:
int run(TreeNode *root)
{
if(root == NULL)
{
return 0;
}
if(root->left == NULL && root->right == NULL)
{
return 1;
}
if(root->left == NULL)
{
return run(root->right) + 1;
}
if(root->right == NULL)
{
return run(root->left) + 1;
}
if(root->left != NULL && root->right != NULL)
{
int leftDepth = run(root->left) + 1;
int rightDepth = run(root->right) + 1;
return (leftDepth > rightDepth) ? rightDepth : leftDepth;
}
return 0;
}
};
根據中序遍歷和後序遍歷結果構建二叉樹
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
//在中序遍歷序列中找到根結點的位置
int findRoot(vector<int> &array, int start, int end, int key)
{
for (int i = start; i <= end; i++)
{
if (array[i] == key)
{
return i;
}
}
return -1;
}
TreeNode *build(vector<int> &inorder, int inStart, int inEnd,
vector<int> &postorder, int postStart, int postEnd)
{
if (inStart > inEnd)
{
return NULL;
}
//根據後序遍歷序列的最後一個數字建立根結點root
TreeNode *root = new TreeNode(postorder[postEnd]);
//獲取根結點的位置position
int position = findRoot(inorder, inStart, inEnd, postorder[postEnd]);
//創建左子樹
root->left = build(inorder, inStart, position - 1,
postorder, postStart,
postStart + (position - inStart - 1));
//創建右子樹
root->right = build(inorder, position + 1, inEnd,
postorder, postStart + (position - inStart),
postEnd - 1);
return root; //返回根結點
}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
{
if(inorder.size() != postorder.size())
return NULL;
return build(inorder, 0, inorder.size() - 1,
postorder, 0, postorder.size() - 1);
}
};