1. 程式人生 > >513.Find Bottom Left Tree Value(DFS)

513.Find Bottom Left Tree Value(DFS)

題目 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.

基本思想: 搜尋節點時,要記錄下樹的深度,時時更新leftval,比較Dep和dep,確保leftval是最後一排的最左邊的值。

程式碼:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        int leftval = 0, Dep = -1; //Dep 是整棵樹的深度
        DFS(root, leftval, Dep, 0);//根節點所處的位置,深度為0
        return leftval;
    }
private:
    void DFS(TreeNode* root, int&leftval, int&Dep, int dep){ //dep是該節點所處的深度
        if(dep>Dep){
            leftval = root->val;
            Dep = dep;
        }
        if(root->left){//左節點非空
            DFS(root->left, leftval, Dep, dep+1);
        }
        if(root->right){//右節點非空
            DFS(root->right, leftval, Dep, dep+1);
        }
    }
};

test: Input: [5,4,7,3,6,2,null,-1,8,9]

Output: -1