码迷,mamicode.com
首页 > 其他好文 > 详细

[Algo] 646. Store Number Of Nodes In Left Subtree

时间:2020-02-21 13:01:03      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:HERE   color   oid   turn   field   col   bin   examples   tree   

Given a binary tree, count the number of nodes in each node’s left subtree, and store it in the numNodesLeft field.

Examples

?

                  1(6)

               /          \

           2(3)        3(0)

          /      \

      4(1)     5(0)

    /        \        \

6(0)     7(0)   8(0)

The numNodesLeft is shown in parentheses.

 

/**
 * public class TreeNodeLeft {
 *   public int key;
 *   public TreeNodeLeft left;
 *   public TreeNodeLeft right;
 *   public int numNodesLeft;
 *   public TreeNodeLeft(int key) {
 *     this.key = key;
 *   }
 * }
 */
public class Solution {
  public void numNodesLeft(TreeNodeLeft root) {
    // Write your solution here
    helper(root);
  }

  private int helper(TreeNodeLeft root) {
    if (root == null) {
      return 0;
    }
    int left = helper(root.left);
    int right = helper(root.right);
    root.numNodesLeft = left;
    return 1 + left + right;
  }
}

 

[Algo] 646. Store Number Of Nodes In Left Subtree

标签:HERE   color   oid   turn   field   col   bin   examples   tree   

原文地址:https://www.cnblogs.com/xuanlu/p/12340807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!