《慕课网玩转算法面试》笔记及习题解答7.1~7.3

来源:互联网 发布:该怎样正确使用网络 编辑:程序博客网 时间:2024/06/05 01:05

LeetCode 104


Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.


思路:简单的递归

    int maxDepth(TreeNode* root) {        if(root == NULL)            return 0;        else            return max(maxDepth(root->left), maxDepth(root->right))+1;    }

LeetCode 111

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.


思路:这道题与104题最大的区别在于, 104题不需要考虑“到叶子节点”这个条件,也就是说,当左右子树中有一个为空的时候,它的返回值应该是非空的子树深度+1,如果直接取min则得到的是当前树的深度,但是当前树的左右子树一空一非空,它不是叶子节点,比如[ [1],[2] ],在1节点,左子树为2,右为空,直接取min,则得到深度为1, 但是1不是叶子节点,2才是,所以这里应该判断左右节点是否为空,然后以非空的节点作为值,如果都非空,则取min

    int minDepth(TreeNode* root) {        if(root == NULL)            return 0;        //当前是叶子节点        if(NULL == root->left && NULL == root->right)            return 1;        //左空右非空,去右边找叶子        if(NULL == root->left && root->right)            return 1 + minDepth(root->right);        //右空左非空,去左边找叶子        if(NULL == root->right && root->left)            return 1+minDepth(root->left);        //左右都非空,左右分别递归        else            return 1 + min( minDepth(root->right), minDepth(root->left) );            }



LeetCode 226

Invert a binary tree.

     4   /   \  2     7 / \   / \1   3 6   9
to
     4   /   \  7     2 / \   / \9   6 3   1

    TreeNode* invertTree(TreeNode* root) {        if(root == NULL)            return root;        root->left = invertTree(root->left);        root->right = invertTree(root->right);        TreeNode* tmp = root->left;        root->left = root->right;        root->right = tmp;        return root;    }

LeetCode 100

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

思路:先判断根节点是否相等,再递归判断左右子树是否相等


    bool isSameTree(TreeNode* p, TreeNode* q) {        if(p == NULL && q == NULL)            return true;        else if(( p == NULL && q!= NULL ) || (p != NULL && q == NULL))            return false;                return (p->val == q->val) && ( isSameTree(p->left, q->left) && ( isSameTree(p->right, q->right) ) );    }


LeetCode 101

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1   / \  2   2 / \ / \3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1   / \  2   2   \   \   3    3

思路:判断左右子树是否对称,再判断左右子树是否相等

    bool _isSymmetric(TreeNode* root1, TreeNode* root2){        if( (root1 && !root2) || (!root1 && root2))            return false;        else if( !root1 && !root2 )            return true;        return ((root1->val == root2->val) && _isSymmetric(root1->right, root2->left) && _isSymmetric(root1->left, root2->right) );    }        bool isSymmetric(TreeNode* root) {        if(root == NULL)            return true;        else            return _isSymmetric(root->left, root->right);    }

LeetCode 222

Given a complete binary tree, count the number of nodes.

思路:因为是完全二叉树,可以通过判断是否为满二叉树来简化计算

    int countNodes(TreeNode* root) {        if(!root)            return 0;        int left_height = 0;        int right_height = 0;        TreeNode* l = root;        TreeNode* r = root;        while(l->left){            left_height++;            l = l->left;        }        while(r->right){            right_height++;            r = r->right;        }        //如果左右的高度一样,那就是满二叉树,可以直接用公式,注意此时的高度需要加上1,因为这时没有算当前节点        if( left_height == right_height) return pow(2, left_height+1)-1;        else            //如果不是满二叉树,那就对左右子树递归,注意加上当前节点+1            return 1 + countNodes(root->left) + countNodes(root->right);    }



LeetCode 110

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.


    int getDepth(TreeNode* root)    {        if(!root)            return 0;        return 1+ max(getDepth(root->left), getDepth(root->right));    }    bool isBalanced(TreeNode* root) {        if(!root)            return true;        //判断左右子树的高度差        if( abs(getDepth(root->left) - getDepth(root->right)) > 1 )            return false;        //判断左右子树是否都是平衡二叉树        return isBalanced(root->left) && isBalanced(root->right);            }

LeetCode 112

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5             / \            4   8           /   / \          11  13  4         /  \      \        7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

思路: 和上面的111类似,需要先判断是否为叶子节点,是则判断,不是则递归

    bool hasPathSum(TreeNode* root, int sum) {        if(NULL == root)            return false;        //当root为叶子节点        if( NULL == root->left && NULL == root->right)            return sum == root->val;        //否则递归        return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);    }


LeetCode 404

Find the sum of all left leaves in a given binary tree.

Example:

    3   / \  9  20    /  \   15   7There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
思路:寻找左边为叶子节点的终止条件

    int sumOfLeftLeaves(TreeNode* root) {        if(root == NULL)            return 0;        //左边为叶子节点时        if(root->left && root->left->left == NULL && root->left->right == NULL)            return root->left->val +sumOfLeftLeaves(root->right);        else            return sumOfLeftLeaves(root->right) + sumOfLeftLeaves(root->left);        }



阅读全文
0 0
原创粉丝点击