是513. 找树左下角的值,这道题里面根节点是否是左节点根本就不统一,它在没有左节点的时候是左节点,在右节点有左叶子的时候又不是左节点。
我把我的代码附上
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int findBottomLeftValue(TreeNode* root) { if(root==nullptr){ return 0; } if(root->left==nullptr&& root->right==nullptr){ return root->val; } int rightdepth = 0; int leftdepth = 0; int rightvalue = 0; int leftvalue = 0; getvalue(root->right, rightvalue, 0,rightdepth); getvalue(root->left, leftvalue, 1,leftdepth); return rightdepth > leftdepth ? rightvalue : leftvalue; } void getvalue(TreeNode* root, int& value, int flag,int& depth) { if (root == nullptr) { return; } depth++; if (root->left == nullptr && root->right == nullptr) { if (flag == 1) { if (root->val > value) { value = root->val; } } } if (root->left) { getvalue(root->left, value, 1, depth); } if (root->right) { getvalue(root->right, value, 0, depth); } } };
标签:right,TreeNode,int,超级,nullptr,愚蠢,root,leetcode,left From: https://www.cnblogs.com/yanzhao-x/p/17059372.html