513. Find Bottom Left Tree Value

方法一:

BFS。用普通BFS来做的话,需要记录结点的depth,每次depth大于max_depth的时候更新答案。或者也可以根据队列的size循环,每次循环第一个就是该层最左边的结点。

有一种巧妙的方法就是按照先右子树后左子树的方式层次遍历,这样最后一个出队列的一定是最左边的结点。

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

 

方法二:

DFS。和BFS思路类似,当depth大于max_depth时更新答案。

class Solution {
public:
    int max_depth=0;
    int res;
    
    int findBottomLeftValue(TreeNode* root) {
        if (root==NULL) return NULL;
        res=root->val;
        dfs(root,0);
        return res;
    }
    
    void dfs(TreeNode *root, int depth){
        if (root==NULL) return;
        if (depth>max_depth){
            max_depth = depth;
            res = root->val;
            cout << res << endl;
        }
        dfs(root->left,depth+1);
        dfs(root->right,depth+1);
    }
};

 

posted @ 2018-06-11 20:49  約束の空  阅读(91)  评论(0)    收藏  举报