Find Bottom Left Tree Value

来源:互联网 发布:怎么分辨mac口红真假 编辑:程序博客网 时间:2024/06/05 09:32

题目:


Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:
Input:


    2
   / \
  1   3


Output:
1
Example 2: 
Input:


        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7


Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.


这道题让我们求二叉树的最左下树结点的值,就是最后一行左边第一个结点的值。


解题思路:

首先想到是用先序遍历来做,因为先序遍历遍历的顺序是左-根-右,所以每一行最左边的结点肯定最先遍历到,那么由于

是新一行,那么当前深度肯定比之前的最大深度大,所以可以更新最大深度为当前深度,结点值result为当前结点值。

但是使用广度优先搜索,对每一层进遍历更简单,result每次保存每一层的第一个值,最后层序遍历完成之后的result即为

最后一行的第一个结点的值。


代码如下:


public:
    int findBottomLeftValue(TreeNode* root) {
        int result = root->val;
        queue<TreeNode *> q;
        q.push(root);
        TreeNode* temp;
        while (!q.empty()) {
            int size = q.size();
            result = q.front()->val;
            while (size--) {
                temp = q.front();
                q.pop();
                if (temp->left != NULL) q.push(temp->left);
                if (temp->right != NULL) q.push(temp->right);
            }
        }
        return result;

    }
};
0 0
原创粉丝点击