zoukankan      html  css  js  c++  java
  • [GeeksForGeeks] Remove all half nodes of a given binary tree

    Given A binary Tree, how do you remove all the half nodes (which has only one child)? Note leaves should not be touched as they have both children as NULL.

    For example consider the below tree.
    tree1

    Nodes 7, 5 and 9 are half nodes as one of their child is Null. We need to remove all such half nodes and return the root pointer of following new tree.

    tree2

    Post order traversal

     1 public class RemoveHalfNodes {
     2     public static TreeNode removeHalfNodes(TreeNode root) {
     3         if(root == null) {
     4             return root;
     5         }
     6         root.left = removeHalfNodes(root.left);
     7         root.right = removeHalfNodes(root.right);
     8         if(root.left == null && root.right != null) {
     9             return root.right;
    10         }
    11         else if(root.left != null && root.right == null) {
    12             return root.left;
    13         }
    14         return root;
    15     }
    16     private static void traverseTree(TreeNode root) {
    17         if(root == null) {
    18             return;
    19         }
    20         String leftVal = root.left == null ? "null" : String.valueOf(root.left.val);
    21         String rightVal = root.right == null ? "null" : String.valueOf(root.right.val);
    22         System.out.println(root.val + " left node: " + leftVal + "; right node: " + rightVal);
    23         traverseTree(root.left);
    24         traverseTree(root.right);
    25     }
    26     public static void main(String[] args) {
    27         TreeNode[] nodes = new TreeNode[8];
    28         for(int i = 0; i < 8; i++) {
    29             nodes[i] = new TreeNode(i);
    30         }
    31         nodes[0].left = nodes[1]; nodes[0].right = nodes[2];
    32         nodes[1].right = nodes[3];
    33         nodes[2].right = nodes[4];
    34         nodes[3].left = nodes[5]; nodes[3].right = nodes[6];
    35         nodes[4].left = nodes[7];
    36         TreeNode root = removeHalfNodes(nodes[0]);
    37         traverseTree(root);
    38     }
    39 }
  • 相关阅读:
    Codeforces Round #681 (Div. 2, based on VK Cup 2019-2020
    浙江农林大学第十九届程序设计竞赛暨天梯赛选拔赛
    Educational Codeforces Round 97 (Rated for Div. 2)
    2018icpc南京区域赛的补题
    天梯赛的一些题目
    djangorestful framework (三)学习
    rest-framework之版本控制
    rest-framework之响应器(渲染器)
    rest-framework之分页器
    rest-framework之频率控制
  • 原文地址:https://www.cnblogs.com/lz87/p/7609274.html
Copyright © 2011-2022 走看看