二叉樹的最大節點 · Binary Tree Maximum Node
常用思想是樹的遍歷,每個節點都不可避免,但是這裏是先分析出兩個節點的比較函數,遞歸找出左右子樹最大的那個數和根節點進行比較,不用比較更小的那個數,相當於減少了一半的工作量。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param root: the root of tree
* @return: the max node
*/
TreeNode* max=NULL;
TreeNode * maxNode(TreeNode * root) {
if(root==NULL) return NULL;
TreeNode* left = maxNode(root->left);
TreeNode* right = maxNode(root->right);
return comp(root,comp(left,right));
}
TreeNode* comp(TreeNode* n1,TreeNode* n2)
{
if(n1==NULL)
return n2;
if(n2==NULL)
return n1;
return n1->val>n2->val?n1:n2;
}
};