二叉樹的最大節點

問題描述:

在二叉樹中尋找值最大的節點並返回。

樣例

給出如下一棵二叉樹:

     1
   /   \
 -5     2
 / \   /  \
0   3 -4  -5 

返回值爲 3 的節點。

解決思路:

創建一個新的節點,將其與根節點比較,然後對左、右子樹遞歸調用,得到結果。

代碼:

class Solution {
public:
    /**
     * @param root the root of binary tree
     * @return the max node
     */ 
     TreeNode *max=new TreeNode(-100000);
    TreeNode *maxNode(TreeNode *root) {
       if(root==NULL) return NULL;
        else{
           if(root->val>max->val) max=root;
           maxNode(root->left);
           maxNode(root->right);
        }
           return max;
        // Write your code here
    }
};

感想:

在定義新節點時寫在了函數內,造成每次遞歸調用時用一遍,使結果錯誤,且在初始化時要儘量小。


發佈了49 篇原創文章 · 獲贊 0 · 訪問量 5009
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章